是否存在最新的快速解决方案,使UITextField占位符消失,或者在用户单击字段时将光标置于前面,而不是在他们开始键入时。我尝试了旧帖子中的一些解决方案,我尝试了下面的代码,但它似乎没有达到预期的效果。任何帮助非常感谢。
class LogInViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var userTextField: UITextField!
// the placeholder text is set in IB, with clear Button set to Appears while editing, and clear when editing begins button checked.
func textFieldDidBeginEditing(textField: UITextField) {
userTextField.placeholder = nil
passwordTextField.placeholder = nil
}
}
这对我有用:
添加userTextField.delegate = self以查看是否加载。 //谢谢我错过了
func textFieldDidBeginEditing(textField: UITextField) {
if userTextField.isFirstResponder() == true {
userTextField.placeholder = nil
}
}
答案 0 :(得分:2)
如果您有多个TextField
1)将String变量添加到您的班级
class YourViewController : UIViewController {
var placeHolder = ""
2)添加UITextFieldDelegate
extension YourViewController : UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
placeHolder = textField.placeholder ?? ""
textField.placeholder = ""
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.placeholder == ""{
textField.placeholder = placeHolder
}
}
答案 1 :(得分:1)
首先要确保从storyboard设置文本字段的委托或在viewDidLoad()
中设置它将代码更改为
userTextField.placeholder = ""
passwordTextField.placeholder = ""
答案 2 :(得分:1)
在Swift 3中
func textFieldDidBeginEditing(_ textField: UITextField) {
if loginTextField.isFirstResponder == true {
loginTextField.placeholder = ""
}
}
答案 3 :(得分:0)
如果您想要一个不可见的占位符(例如,创建自己的自定义文本字段),则可以覆盖此方法:
public override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return .zero
}
答案 4 :(得分:0)
创建UITextField的子类:
class CustomTextField: UITextField {
private var placeholderBackup: String?
override func becomeFirstResponder() -> Bool {
placeholderBackup = placeholder
placeholder = nil
return super.becomeFirstResponder()
}
override func resignFirstResponder() -> Bool {
placeholder = placeholderBackup
return super.resignFirstResponder()
}
}