【问题标题】:SwiftUI - How do I change the text color of a Textfield?SwiftUI - 如何更改文本字段的文本颜色?
【发布时间】:2019-11-05 00:15:38
【问题描述】:

我正在尝试在 SwiftUI 中更改 Textfield(用户编写的文本)的文本颜色。我正在尝试使用foregroundColor,但它会更改占位符的文本颜色。

你如何在 SwiftUI 中做到这一点?

 TextField($variable, placeholder: Text("a text"))
            .foregroundColor(.green)

【问题讨论】:

  • Xcode 11 beta 3 修复了这个问题。
  • 但是现在如何更改占位符颜色?大声笑

标签: swift colors textcolor swiftui


【解决方案1】:

.foregroundColor 实际上确实改变了TextField 的文本颜色,但只有当它具有默认值时,例如这样才能正常工作:

TextField(.constant("Hello World"), placeholder: Text("Type here..."))
  .foregroundColor(.green)

但是,一旦您删除整个文本,文本字段不仅会丢失其颜色,还会丢失其他修饰符,例如对齐方式。这可能是当前版本中的一个错误,所以我会提交一个错误报告。


更新:此问题已在 Xcode 11 beta 3 中得到修复。

【讨论】:

  • 自 Xcode 11 正式发布(或可能更早)以来,似乎不再可能有 Text 占位符。
【解决方案2】:

使用background()设置背景颜色,foreground()设置输入文本颜色

struct PlaygroundTestView: 查看 {

@State var searchText = ""

var body: some View {
    
    TextField("Search", text: $searchText)
    .font(Font.system(size: 14))
    .padding()
    .background(RoundedRectangle(cornerRadius: 50).fill(Color.white))
    
    .foregroundColor(.black)
    .padding()
    .offset(x:8, y: 10)
}

}

【讨论】:

  • 现在在 Xcode 12 / iOS14 中是否损坏/无法工作?我已尝试设置前景色、背景色和 .bold,如此处所述,但我得到的只是一个浅灰色且几乎不可读的文本。
  • “浅灰色,大部分不可读文本”是占位符文本。输入文本设置为黑色。这适用于 Catalina/xcode 12。
【解决方案3】:

应更改文本颜色以使用文本字段的属性.foreground color 更新为Xcode Version 11.1 (11A1027)

SwiftUI

TextField("Email", text: $email)
                .textContentType(.emailAddress)
                .padding(.init(top: 0, leading: 15, bottom:0 , trailing: 15))
                .foregroundColor(.blue)
                .textFieldStyle(RoundedBorderTextFieldStyle.init())

【讨论】:

    【解决方案4】:
    foregroundColor does it.
    
                    Text("TEXT")
                        .font(.footnote)
                        .bold()
                        .foregroundColor(Color("ColorAccentWhite"))
                        .background(Color("ColorGrayTwo"))
                        .cornerRadius(2)
    

    【讨论】:

      猜你喜欢
      • 2021-01-06
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      相关资源
      最近更新 更多