---
title: "Hiển thị biểu đồ mục tiêu cân nặng tương tác trong paywall"
description: "Hiển thị cân nặng dự kiến của từng người dùng dưới dạng biểu đồ trong flow paywall. Người dùng kéo dọc biểu đồ để xem cân nặng theo từng tuần."
---

> **AI agents**: to search Adapty docs faster and with fewer tokens, install the Adapty skills: `npx adapty skills install --yes`

Hãy làm theo hướng dẫn này để hiển thị biểu đồ cân nặng dự kiến của từng người dùng trong một paywall flow. Người dùng nhập cân nặng hiện tại và mục tiêu của họ trong onboarding flow. Ứng dụng của bạn thu thập cả hai giá trị này. Biểu đồ hiển thị tiến độ hàng tuần mà người dùng có thể kỳ vọng khi sử dụng ứng dụng của bạn, từ giá trị này đến giá trị kia. Ứng dụng của bạn render biểu đồ dưới dạng Swift Charts view native trong một [custom element](flow-custom-elements).

:::tip
Công thức này chỉ áp dụng cho ứng dụng iOS. Ứng dụng được xây dựng bằng các framework khác chỉ hiển thị [nội dung dự phòng](flow-custom-elements#set-fallback-content) của các thành phần tùy chỉnh. Hỗ trợ cho Android và các framework đa nền tảng sẽ sớm ra mắt.
:::

## Trước khi bắt đầu \{#before-you-start\}

- Cập nhật ứng dụng lên Adapty iOS SDK 4.4 trở lên. Các phiên bản SDK cũ hơn sẽ hiển thị [nội dung dự phòng](flow-custom-elements#set-fallback-content) cho mọi phần tử tùy chỉnh.
- Thiết lập ứng dụng để [tải](get-pb-paywalls) và [hiển thị](ios-present-paywalls) các flow.
- Tạo hai flow riêng biệt — một cho onboarding và một cho paywall. Thêm mỗi flow vào một [placement](placements). Mã trong bài hướng dẫn này tải flow paywall từ placement có ID `weight_paywall`.

## 1. Hỏi cân nặng hiện tại và mục tiêu trong onboarding flow \{#1-ask-for-the-current-and-goal-weight-in-the-onboarding-flow\}

Trong Flow & Paywall Builder, thêm hai [input **Number**](builder-inputs-and-forms) vào onboarding flow:

- Một ô nhập cân nặng hiện tại theo kilogram, với **Element ID** là `weight`.
- Một ô nhập cân nặng mục tiêu theo kilogram, với **Element ID** là `goal_weight`.

Để đảm bảo ứng dụng đọc trọng lượng theo cùng một cách ở mọi ngôn ngữ, hãy chọn **Integer** trong dropdown **Format** của cả hai input. Mỗi input gửi giá trị của nó đến ứng dụng dưới dạng văn bản, đúng như người dùng đã nhập. Đoạn code trong recipe này xử lý "70.5" và "70,5" theo hai cách khác nhau. Số nguyên không có dấu phân cách thập phân.

Để đảm bảo ứng dụng nhận được cả hai giá trị, hãy kết thúc flow onboarding bằng một màn hình không có input nào. Trên màn hình đó, thêm một nút với action [**Close flow**](onboarding-actions#close-flow). Các input gửi giá trị của chúng khi mất focus hoặc khi người dùng chuyển sang màn hình khác.

## 2. Thêm phần tử tùy chỉnh vào màn hình paywall \{#2-add-the-custom-element-to-the-paywall-screen\}

Trong flow paywall, [thêm một phần tử tùy chỉnh](flow-custom-elements#add-and-configure) vào màn hình và cấu hình cho biểu đồ:

- **Type**: `line_chart`.
- **ID**: `weight_goal`.
- **Height**: Giữ nguyên chiều cao **Fixed** mặc định. Biểu đồ sẽ lấp đầy phần tử tùy chỉnh.

Hãy đặt phần tử tùy chỉnh ngoài các container phản hồi thao tác chạm, chẳng hạn như carousel. Nếu không, kéo dọc theo biểu đồ cũng sẽ làm di chuyển carousel.

Bên trong custom element, thêm một [**Image**](custom-media#image) với biểu đồ cân nặng mẫu. Người dùng sẽ thấy ảnh này như nội dung [dự phòng](flow-custom-elements#set-fallback-content) khi phiên bản ứng dụng của họ không hiển thị được biểu đồ.

## 3. Lưu cân nặng hiện tại và mục tiêu trong ứng dụng \{#3-save-the-current-and-goal-weight-in-your-app\}

Thu thập cân nặng hiện tại và mục tiêu từ các sự kiện `flow_user_input` của onboarding flow, như trong [Xử lý dữ liệu từ các flow](ios-flow-input). Để biết người dùng đã đến màn hình cuối cùng, hãy theo dõi sự kiện `flow_screen_showed` với `is_last_screen` được đặt thành `true`. Khi onboarding flow đóng lại sau màn hình đó, truyền cả hai giá trị cân nặng vào `showWeightPaywall`, phương thức [mở paywall flow với biểu đồ](#5-match-the-chart-to-the-custom-element).

Đoạn code sau đây dành cho UIKit. Một view controller đóng vai trò là delegate của cả hai flow. Nó cũng phải implement các phương thức purchase và restore của protocol `AdaptyFlowControllerDelegate`. Ví dụ này bỏ qua chúng. Để xem chi tiết, hãy đến [Hiển thị flow và paywall trong UIKit](ios-present-paywalls#present-flows-and-paywalls-in-uikit).

<Tabs groupId="current-os" queryString>
<TabItem value="ios" label="iOS" default>

```swift showLineNumbers title="Swift"
private var enteredWeights: [String: String] = [:]
private var reachedLastScreen = false

func flowController(
    _ controller: AdaptyFlowController,
    didReceiveAnalyticEvent name: String,
    params: [String: any Sendable]
) {
    if name == "flow_screen_showed", params["is_last_screen"] as? Bool == true {
        reachedLastScreen = true
        return
    }
    guard name == "flow_user_input",
          let elementId = params["element_id"] as? String,
          let value = params["value"] as? String
    else { return }

    enteredWeights[elementId] = value
}

func flowControllerDidDisappear(_ controller: AdaptyFlowController) {
    // This delegate receives events from both flows. Reset the entered
    // weights whenever a flow disappears, so that the paywall doesn't open
    // again when the user closes it.
    let weights = enteredWeights
    let finished = reachedLastScreen
    enteredWeights.removeAll()
    reachedLastScreen = false

    // Number inputs send their values as strings
    guard finished,
          let currentWeight = weights["weight"].flatMap({ Double($0) }),
          let goalWeight = weights["goal_weight"].flatMap({ Double($0) })
    else { return }

    Task {
        await showWeightPaywall(currentWeight: currentWeight, goalWeight: goalWeight)
    }
}
```

</TabItem>
</Tabs>

Trong SwiftUI, hãy dùng các closure `didReceiveAnalyticEvent` và `didDisappear` của modifier `.flow` thay vì các phương thức delegate. Hiển thị paywall flow bằng modifier `.flow` thứ hai.

## 4. Tạo chart view \{#4-create-the-chart-view\}

Tạo một model cho kế hoạch cân nặng và một SwiftUI view với biểu đồ. Kế hoạch có một mục nhập mỗi tuần, từ cân nặng hiện tại đến cân nặng mục tiêu. Khi người dùng kéo dọc theo biểu đồ, view đánh dấu tuần tại điểm chạm và hiển thị cân nặng dự kiến cho tuần đó:

<Tabs groupId="current-os" queryString>
<TabItem value="ios" label="iOS" default>

```swift showLineNumbers title="Swift"

struct WeightPlan {
    let entries: [WeightEntry]

    // One entry per week, from the current weight to the goal weight
    init(currentWeight: Double, goalWeight: Double) {
        let weeklyChange = 0.5 // kg per week
        let startDate = Date.now
        let weeks = Int((abs(goalWeight - currentWeight) / weeklyChange).rounded(.up))
        let step = goalWeight < currentWeight ? -weeklyChange : weeklyChange
        entries = (0...weeks).map { week in
            WeightEntry(
                date: startDate.addingTimeInterval(Double(week) * 7 * 24 * 60 * 60),
                kilograms: week == weeks ? goalWeight : currentWeight + step * Double(week)
            )
        }
    }
}

struct WeightEntry: Identifiable {
    let date: Date
    let kilograms: Double
    var id: Date { date }
}

@available(iOS 16.0, *) // Swift Charts needs iOS 16
struct WeightGoalChart: View {
    let entries: [WeightEntry]
    @State private var selectedDate: Date?

    // The entry closest to the date that the user drags to
    private var selectedEntry: WeightEntry? {
        guard let selectedDate else { return nil }
        return entries.min {
            abs($0.date.timeIntervalSince(selectedDate)) < abs($1.date.timeIntervalSince(selectedDate))
        }
    }

    var body: some View {
        if #available(iOS 17.0, *) {
            chart.chartXSelection(value: $selectedDate)
        } else {
            chart // iOS 16: no drag selection
        }
    }

    private var chart: some View {
        Chart {
            ForEach(entries) { entry in
                LineMark(
                    x: .value("Date", entry.date),
                    y: .value("Weight", entry.kilograms)
                )
            }
            if let selectedEntry {
                RuleMark(x: .value("Date", selectedEntry.date))
                    .foregroundStyle(.gray.opacity(0.3))
                PointMark(
                    x: .value("Date", selectedEntry.date),
                    y: .value("Weight", selectedEntry.kilograms)
                )
                .annotation(position: .top) {
                    Text("\(selectedEntry.kilograms, specifier: "%.1f") kg")
                        .font(.caption.bold())
                }
            }
        }
        .chartYScale(domain: .automatic(includesZero: false))
    }
}
```

</TabItem>
</Tabs>

Kế hoạch giả định rằng cân nặng thay đổi 0,5 kg mỗi tuần. Để sử dụng tốc độ khác, hãy chỉnh sửa `weeklyChange`.

Tính năng kéo theo biểu đồ yêu cầu iOS 17 trở lên. Trên iOS 16, người dùng thấy đường kẻ nhưng không thể kéo dọc theo nó.

## 5. Khớp biểu đồ với phần tử tùy chỉnh \{#5-match-the-chart-to-the-custom-element\}

Viết một [resolver](ios-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views) trả về view biểu đồ cho Type `line_chart` và ID `weight_goal`. Lưu kế hoạch cân nặng trong một thuộc tính của resolver:

<Tabs groupId="current-os" queryString>
<TabItem value="ios" label="iOS" default>

```swift showLineNumbers title="Swift"

@available(iOS 16.0, *) // the chart needs iOS 16
struct WeightChartResolver: AdaptyUICustomElementsResolver {
    let plan: WeightPlan

    func view(
        forType type: String,
        id: String,
        context: AdaptyUICustomElementContext
    ) -> AnyView? {
        guard type == "line_chart", id == "weight_goal" else {
            return nil // another custom element: show the fallback
        }
        return AnyView(WeightGoalChart(entries: plan.entries))
    }
}
```

</TabItem>
</Tabs>

Đính kèm resolver vào paywall flow khi bạn lấy cấu hình của nó. Tạo resolver với kế hoạch trọng lượng từ trọng lượng hiện tại và mục tiêu:

<Tabs groupId="current-os" queryString>
<TabItem value="ios" label="iOS" default>

```swift showLineNumbers title="Swift"
func showWeightPaywall(currentWeight: Double, goalWeight: Double) async {
    let plan = WeightPlan(currentWeight: currentWeight, goalWeight: goalWeight)
    do {
        let flow = try await Adapty.getFlow(placementId: "weight_paywall")
        let flowConfiguration = try await AdaptyUI.getFlowConfiguration(
            forFlow: flow,
            customElementsResolver: WeightChartResolver(plan: plan)
        )
        let flowController = try AdaptyUI.flowController(
            with: flowConfiguration,
            delegate: self
        )
        present(flowController, animated: true)
    } catch {
        // handle the error
    }
}
```

</TabItem>
</Tabs>

Nếu ứng dụng của bạn đã thiết lập [resolver toàn ứng dụng](ios-flow-custom-elements#set-an-app-wide-resolver), resolver này sẽ thay thế nó trong paywall flow. `WeightChartResolver` trả về `nil` cho bất kỳ Type và ID nào khác, vì paywall flow trong hướng dẫn này không có custom element nào khác. Nếu paywall flow của bạn có các custom element khác, hãy truyền resolver toàn ứng dụng vào resolver này. Sau đó gọi resolver toàn ứng dụng cho các Type và ID của chúng, như trong [Gắn resolver vào một flow](ios-flow-custom-elements#attach-a-resolver-to-one-flow).

## 6. Kiểm tra trên thiết bị \{#6-test-on-a-device\}

Flow & Paywall Builder không thể chạy code của ứng dụng, vì vậy canvas chỉ hiển thị fallback. Để xem trước biểu đồ:

1. [Xuất bản cả hai flow](builder-save-publish). Để xem phiên bản mới nhất đã xuất bản thay vì phiên bản được lưu trong bộ nhớ đệm, hãy đăng ký thiết bị làm [thiết bị kiểm thử](test-devices).
2. Chạy bản build ứng dụng của bạn có chứa resolver, trên iOS 17 trở lên. Hoàn thành flow onboarding với cân nặng hiện tại và cân nặng mục tiêu. Xác minh rằng đường trên biểu đồ bắt đầu ở cân nặng hiện tại và kết thúc ở cân nặng mục tiêu.
3. Kéo dọc theo biểu đồ và xác minh rằng cân nặng dự kiến cho tuần mà bạn đang chỉ vào hiển thị phía trên đường kẻ.

Để kiểm tra fallback, hãy xóa đối số `customElementsResolver` khỏi lệnh gọi `getFlowConfiguration`, rồi mở lại paywall flow.

Để tìm hiểu lý do tại sao fallback hiển thị thay vì biểu đồ, hãy làm theo hướng dẫn trong phần [Kiểm tra trên thiết bị](ios-flow-custom-elements#test-on-a-device) của tài liệu iOS.