簡體   English   中英

如何手動添加在文本字段中單擊時消失的UITextField占位符文本?

[英]How to manually add UITextField placeholder text that disappears when clicked inside textfield?

我目前有一個自定義文本字段,因此添加占位符文本的情節提要方法無法正常工作。 現在,我在viewDidLoad中使用此代碼,但是當我在文本字段中單擊時,占位符文本仍然保留。

  usernameOrEmailTextField.text = "Username or email"
    usernameOrEmailTextField.textColor = UIColor.whiteColor()

有沒有一種方法可以使文本在單擊文本字段時消失,以便用戶可以為文本字段鍵入自己的信息?

這是我的自定義文本字段:

class CustomTextField: UITextField{

  required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!

//Border
self.layer.cornerRadius = 10.0;
self.layer.borderWidth = 0.75
self.layer.borderColor = UIColor.whiteColor().CGColor
//Background
self.backgroundColor = UIColor(white: 1, alpha: 0.0)

//Text
self.textColor = UIColor.whiteColor()
self.textAlignment = NSTextAlignment.Left
  }

}

我嘗試使用.placeholder而不是.text:

  usernameOrEmailTextField.placeholder = "Username or email"
usernameOrEmailTextField.textColor = UIColor.whiteColor()

但文本字段似乎為空白。

找出問題所在。 textField.placeholder = "Some text..."確實起作用,只是我的背景是深色,所以我看不到占位符文本。

不幸的是,文本視圖沒有占位符文本選項。

您正在做的是更改文本字段的文本,點擊該文本字段不會消失。

如果可以的話,可以使用UITextField。 在這種情況下,您可以使用textFieldName.placeholder =“ Enter text”,這將起作用。

但是要回答實際問題,我過去所做的方法是將UILabel放在UITextField之上,然后使用文本視圖的委托方法在用戶輕按時隱藏/顯示標簽。

示例:如果用戶didBeginEditing文本字段隱藏標簽,如果用戶didEndEditing則隱藏標簽,請檢查其中的文本是否為空,如果是,則顯示標簽,否則不顯示。

編輯:要明確,對我來說,似乎您使用的是TextView,但說的是TextField。 包括IBOutlet無疑會向我們展示。

您可以為其使用委托方法textFieldShouldBeginEditing(textField:)

class ViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet var textField: CustomTextField!

  override func viewDidLoad() {
    super.viewDidLoad()

    textField.placeholder = "Some text..."
  }

  func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    textField.placeholder = ""
    return true
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM