为 Swift 4 更新
UITextView 本身没有占位符属性,因此您必须使用UITextViewDelegate 方法以编程方式创建和操作一个。我建议根据所需的行为使用下面的解决方案 #1 或 #2。
注意:对于任一解决方案,将UITextViewDelegate 添加到类并设置textView.delegate = self 以使用文本视图的委托方法。
解决方案 #1 - 如果您希望占位符在用户选择文本视图后立即消失:
首先将UITextView 设置为包含占位符文本并将其设置为浅灰色以模仿UITextField 的占位符文本的外观。在viewDidLoad 中或在创建文本视图时这样做。
textView.text = "Placeholder"
textView.textColor = UIColor.lightGray
然后当用户开始编辑文本视图时,如果文本视图包含占位符(即如果其文本颜色为浅灰色),则清除占位符文本并将文本颜色设置为黑色以适应用户的输入。
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.textColor == UIColor.lightGray {
textView.text = nil
textView.textColor = UIColor.black
}
}
然后,当用户完成对文本视图的编辑并辞去第一响应者的职务时,如果文本视图为空,则通过重新添加占位符文本并将其颜色设置为浅灰色来重置其占位符。
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Placeholder"
textView.textColor = UIColor.lightGray
}
}
解决方案 #2 - 如果您希望在文本视图为空时显示占位符,即使文本视图已被选中:
先在viewDidLoad中设置占位符:
textView.text = "Placeholder"
textView.textColor = UIColor.lightGray
textView.becomeFirstResponder()
textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
(注意:由于 OP 希望在视图加载后立即选择文本视图,因此我将文本视图选择合并到上述代码中。如果这不是您想要的行为并且您不希望选择文本视图查看加载,从上面的代码块中删除最后两行。)
然后使用shouldChangeTextInRange UITextViewDelegate 方法,如下所示:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// Combine the textView text and the replacement text to
// create the updated text string
let currentText:String = textView.text
let updatedText = (currentText as NSString).replacingCharacters(in: range, with: text)
// If updated text view will be empty, add the placeholder
// and set the cursor to the beginning of the text view
if updatedText.isEmpty {
textView.text = "Placeholder"
textView.textColor = UIColor.lightGray
textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
}
// Else if the text view's placeholder is showing and the
// length of the replacement string is greater than 0, set
// the text color to black then set its text to the
// replacement string
else if textView.textColor == UIColor.lightGray && !text.isEmpty {
textView.textColor = UIColor.black
textView.text = text
}
// For every other case, the text should change with the usual
// behavior...
else {
return true
}
// ...otherwise return false since the updates have already
// been made
return false
}
并且还实现textViewDidChangeSelection 以防止用户在占位符可见时更改光标的位置。 (注意:textViewDidChangeSelection 在视图加载之前被调用,所以只有在窗口可见时才检查文本视图的颜色):
func textViewDidChangeSelection(_ textView: UITextView) {
if self.view.window != nil {
if textView.textColor == UIColor.lightGray {
textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
}
}
}