swiftui-example
swiftui-example copied to clipboard
使用 Swift 更改占位符(placeholder)文本颜色
您可以使用属性字符串设置占位符文本。 通过属性传递所需的颜色:
SwiftUI 使用
struct ContentView: View {
@State var text = ""
var body: some View {
ZStack(alignment: .leading) {
if text.isEmpty { Text("Placeholder").foregroundColor(.red) }
TextField("", text: $text)
}
}
}
var myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
myTextField.backgroundColor = .blue
myTextField.attributedPlaceholder = NSAttributedString(
string: "placeholder text",
attributes: [NSForegroundColorAttributeName: UIColor.yellow]
)
Swift 3+ 使用以下内容:
myTextField.attributedPlaceholder = NSAttributedString(
string: "placeholder text",
attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]
)
Swift 4.2 使用以下内容:
myTextField.attributedPlaceholder = NSAttributedString(
string: "placeholder text",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]
)
设置占位符
import SwiftUI
public struct PlaceholderStyle: ViewModifier {
var showPlaceHolder: Bool
var placeholder: String
public func body(content: Content) -> some View {
ZStack(alignment: .leading) {
if showPlaceHolder {
Text(placeholder)
.padding(.horizontal, 15)
}
content
.foregroundColor(Color.white)
.padding(5.0)
}
}
}
struct ContentView: View {
@State var text = ""
var body: some View {
TextField("", text: $text)
.modifier(
PlaceholderStyle(showPlaceHolder: text == "", placeholder: "My Placeholder")
)
}
}