如何为还没有任何数据的Swift图表添加占位符?

plicqrtu  于 2022-11-28  发布在  Swift
关注(0)|答案(1)|浏览(112)

假设这个图表没有任何数据,我用什么api来显示“no data yet”这样的占位符呢?我搜索了WWDC和apple docs。
也许这只是一个隐藏图表和显示一些文本的情况。

import SwiftUI
import Charts

struct TopStyleChart: View {
    let data = [
        (name: "Cachapa", sales: 916),
        (name: "Injera", sales: 850),
        (name: "Crêpe", sales: 802),
        (name: "Jian Bing", sales: 753),
        (name: "Dosa", sales: 654),
        (name: "American", sales: 618)
    ]

    var body: some View {
        Chart(data, id: \.name) {
            BarMark(
                x: .value("Sales", $0.sales),
                y: .value("Name", $0.name)
            )
            // Set the foreground style of the bars.
            .foregroundStyle(.pink)
            // Customize the accessibility label and value.
            .accessibilityLabel($0.name)
            .accessibilityValue("\($0.sales) sold")
        }
    }
}
arknldoa

arknldoa1#

一个简单的if子句就可以解决这个问题:

struct TopStyleChart: View {
    let data: [(name: String, sales: Int)]?

    var body: some View {
        if let data = data{
            Chart(data, id: \.name) {
                BarMark(
                    x: .value("Sales", $0.sales),
                    y: .value("Name", $0.name)
                )
                // Set the foreground style of the bars.
                .foregroundStyle(.pink)
                // Customize the accessibility label and value.
                .accessibilityLabel($0.name)
                .accessibilityValue("\($0.sales) sold")
            }
        } else{
            Text("no data yet")
        }
    }
}

相关问题