swift - 在选取器中对齐视图
问题描述
如何将Color
视图与文本对齐成一条直线?
看起来像这样(文本对齐前导):
█ 红色
█ 绿色
█ 蓝色
或者这个(文本居中对齐):
█ 红色
█ 绿色
█ 蓝色
当前代码:
struct ContentView: View {
@State private var colorName: Colors = .red
var body: some View {
Picker("Select color", selection: $colorName) {
ForEach(Colors.allCases) { color in
HStack {
color.asColor.aspectRatio(contentMode: .fit)
Text(color.rawValue)
}
}
}
}
}
enum Colors: String, CaseIterable, Identifiable {
case red
case green
case blue
var id: String { rawValue }
var asColor: Color {
switch self {
case .red: return .red
case .green: return .green
case .blue: return .blue
}
}
}
结果(未正确对齐):
没有Picker
,我发现可以使用alignmentGuide(_:computeValue:)
来实现结果。但是,这需要在Picker
.
试图:
VStack(alignment: .custom) {
ForEach(Colors.allCases) { color in
HStack {
color.asColor.aspectRatio(contentMode: .fit)
.alignmentGuide(.custom) { d in
d[.leading]
}
Text(color.rawValue)
.frame(maxWidth: .infinity)
.fixedSize()
}
}
.frame(height: 50)
}
/* ... */
extension HorizontalAlignment {
struct CustomAlignment: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
return context[HorizontalAlignment.leading]
}
}
static let custom = HorizontalAlignment(CustomAlignment.self)
}
尝试结果:
解决方案
可能的解决方案是对使用视图首选项计算的最大标签应用的标签使用动态宽度。
这是一个演示。使用 Xcode 13beta / iOS15 测试
注意:ViewWidthKey
取自我的其他答案https://stackoverflow.com/a/63253241/12299030
struct ContentView: View {
@State private var colorName: Colors = .red
@State private var maxWidth = CGFloat.zero
var body: some View {
Picker("Select color", selection: $colorName) {
ForEach(Colors.allCases) { color in
HStack {
color.asColor.aspectRatio(contentMode: .fit)
Text(color.rawValue)
}
.background(GeometryReader {
Color.clear.preference(key: ViewWidthKey.self,
value: $0.frame(in: .local).size.width)
})
.onPreferenceChange(ViewWidthKey.self) {
self.maxWidth = max($0, maxWidth)
}
.frame(minWidth: maxWidth, alignment: .leading)
}
}
}
}
推荐阅读
- r - ggplot2中两条密度曲线的单独stat_density
- python - 从 / 导入 Python 文件
- javascript - D3 数据显示的差异
- azure - 当服务计划位于不同的资源组中时如何部署 Azure Functions 应用程序
- c# - 了解 Odata 更新查询
- javascript - Vuetable 2 不在浏览器中显示
- php - 如何在 PHP 中发布 iframe 代码
- sql-server - SQL Pivot(?) - 展平按天/事件选择以包含整周的列
- python - 为什么 HITBTC V2 REST API 返回 2001 错误(不正确的对)?
- excel - 计算特定日期条件内的出现次数