如何在SwiftUI中修改表单标签的文字颜色
解决方案
通用兼容方案(支持iOS 13及以上所有版本)
直接放弃使用输入控件自带的标题参数,手动拆分标签和输入组件,完全自定义各自的样式,可适配所有表单控件场景:
// 1. 自定义TextField样式 HStack { Text("Kundennummer") .foregroundColor(.gray) // 标签设置灰色 Spacer() TextField("", text: $customerNumber) .foregroundColor(.white) // 输入值设置白色 .multilineTextAlignment(.trailing) } // 2. 自定义Picker样式 HStack { Text("Anrede") .foregroundColor(.gray) Spacer() Picker("", selection: $previewIndex) { ForEach(0 ..< previewOptions.count) { Text(self.previewOptions[$0]) .foregroundColor(.white) } } .pickerStyle(.menu) .foregroundColor(.white) } // 3. 自定义Section头部样式 Section(header: Text("Kontakt") .foregroundColor(.gray) // 直接给头部Text设置颜色 ) { HStack { Text("Telefon") .foregroundColor(.gray) Spacer() TextField("", text: $phone) .foregroundColor(.white) .multilineTextAlignment(.trailing) } }
这种方式灵活性最高,所有样式都可以自主控制,不受系统版本限制,实现效果如下:
iOS 16+ 简化方案
如果不需要兼容iOS 15及更低版本,可以用系统提供的LabeledContent配合样式修饰符快速实现:
Form { LabeledContent("Kundennummer") { TextField("", text: $customerNumber) .foregroundColor(.white) } LabeledContent("Anrede") { Picker("", selection: $previewIndex) { ForEach(0 ..< previewOptions.count) { Text(self.previewOptions[$0]) } } .foregroundColor(.white) } Section("Kontakt") { LabeledContent("Telefon") { TextField("", text: $phone) .foregroundColor(.white) } } } // 全局统一设置所有LabeledContent的标签颜色 .foregroundColor(.gray)
如果需要单独修改某一个标签的颜色,直接给对应的LabeledContent添加.foregroundColor修饰符即可。
内容的提问来源于stack exchange,提问作者Nikolass
相关产品推荐
相关产品推荐

