Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jaywcjlove opened this issue May 2, 2021 · 1 comment
Open

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

jaywcjlove opened this issue May 2, 2021 · 1 comment
Labels

Comments

@jaywcjlove
Copy link
Owner

jaywcjlove commented May 2, 2021

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

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
Copy link
Owner Author

jaywcjlove commented May 8, 2021

设置占位符

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant