You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI饼图文本居中与选中扇区透明度调整问题求助

解决SwiftUI饼图文本居中与扇区高亮问题

问题1:文本居中修复

当前VStack仅包裹文本内容,未占满ZStack的可用空间,导致文本无法精准对齐饼图中央。只需给VStack添加frame(maxWidth: .infinity, maxHeight: .infinity),让它填充整个ZStack区域,内部文本自然会基于饼图范围居中:

VStack(alignment: .center) {
    Text("Token Allocation")
        .font(.callout)
        .foregroundStyle(.secondary)
    
    Text(String(format: "%.2f", selectedBalance ?? 0.0)) // 可选优化:格式化数字避免多位小数
        .font(.system(size: 20))
        .foregroundColor(.primary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity) // 关键修改

问题2:扇区透明度高亮

通过给SectorMark添加opacity修饰符,根据当前扇区的余额是否匹配选中值动态调整透明度,同时处理selectedBalance的可选值与浮点数精度问题:

SectorMark(
    angle: .value("Balance", Int(tokenHolder.balance)!),
    innerRadius: .ratio(0.618),
    angularInset: 1.5
)
.cornerRadius(4)
.foregroundStyle(by: .value("Names", tokenHolder.name))
.opacity(
    guard let selected = selectedBalance else { return 0.3 }
    return abs(tokenHolder.balance - selected) < 0.001 ? 1.0 : 0.3
) // 未选中扇区30%透明度,选中扇区100%高亮

完整修改后的代码

struct TokenAllocationChartView: View {
    let tokenHolders: [Token]
    @Binding var selectedBalance: Double?
    
    var body: some View {
        ZStack {
            Chart(tokenHolders) { tokenHolder in
                SectorMark(
                    angle: .value("Balance", Int(tokenHolder.balance)!),
                    innerRadius: .ratio(0.618),
                    angularInset: 1.5
                )
                .cornerRadius(4)
                .foregroundStyle(by: .value("Names", tokenHolder.name))
                .opacity(
                    guard let selected = selectedBalance else { return 0.3 }
                    return abs(tokenHolder.balance - selected) < 0.001 ? 1.0 : 0.3
                )
            }
            .chartAngleSelection(value: $selectedBalance)
            .frame(height: 300)
            
            VStack(alignment: .center) {
                Text("Token Allocation")
                    .font(.callout)
                    .foregroundStyle(.secondary)
                
                Text(String(format: "%.2f", selectedBalance ?? 0.0))
                    .font(.system(size: 20))
                    .foregroundColor(.primary)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
    }
}

内容的提问来源于stack exchange,提问作者Alexander Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 19:42:45