I'm working with SwiftUI to create a pie chart using SectorMark in a Chart view. I have two challenges:
I'm struggling to center text in the middle of the pie chart. The text should display the selected token's balance, but it's not aligning correctly in the center.
I want to set a low opacity for all sectors and then highlight the selected sector by changing its opacity to a brighter color. Any suggestions on how to center the text properly and adjust the sector opacity for selection would be greatly appreciated.
Here's the relevant part of my code:
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))
}
.chartAngleSelection(value: $selectedBalance)
.frame(height: 300)
VStack(alignment:.center) {
Text("Token Allocation")
.font(.callout)
.foregroundStyle(.secondary)
Text(String(selectedBalance ?? 0.0))
.font(.system(size: 20))
.foregroundColor(.primary)
}
}
}
}
I managed to solve your two issues thanks to a similar test app I had. Here's the code:
The key part is the findToken function which takes in the current double value selected and finds the correct token name whose that fits that value. For higlighting the pie chart the opacity modifer is just what we need, and to center the Text inside the chart you just need the height to the Token Allocation text and set maxHeight for the enclosing VStack. The Result: