swiftui-example icon indicating copy to clipboard operation
swiftui-example copied to clipboard

使用 Swift 更改占位符(placeholder)文本颜色

Open jaywcjlove opened this issue 4 years ago • 1 comments

您可以使用属性字符串设置占位符文本。 通过属性传递所需的颜色:

SwiftUI 使用

struct ContentView: View {
    @State var text = ""
    var body: some View {
        ZStack(alignment: .leading) {
            if text.isEmpty { Text("Placeholder").foregroundColor(.red) }
            TextField("", text: $text)
        }
    }
}
iShot2021-05-09 02 37 53
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]
)

jaywcjlove avatar May 02 '21 17:05 jaywcjlove

设置占位符

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")
        )
    }
}

jaywcjlove avatar May 08 '21 18:05 jaywcjlove