我正在尝试将占位符放入我的 UITextView 中,并在此处使用这段代码找到了解决方案:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let currentText:NSString = storyView.text
let updatedText = currentText.stringByReplacingCharactersInRange(range, withString:text)
if updatedText.isEmpty {
storyView.text = "Write out your story here!"
storyView.textColor = UIColor.lightGrayColor()
storyView.selectedTextRange = storyView.textRangeFromPosition(storyView.beginningOfDocument, toPosition: storyView.beginningOfDocument)
return false
}else if storyView.textColor == UIColor.lightGrayColor() && !text.isEmpty {
storyView.text = nil
storyView.textColor = UIColor.blackColor()
}
return true
}
func textViewDidChangeSelection(storyView: UITextView) {
if self.view.window != nil {
if storyView.textColor == UIColor.lightGrayColor() {
storyView.selectedTextRange = storyView.textRangeFromPosition(storyView.beginningOfDocument, toPosition: storyView.beginningOfDocument)
}
}
}
它有效,我对此很满意,但我想将它应用于同一个 ViewController 中的其他 UITextView。如果不创建 textView 方法的重复实例,我该怎么做?
最佳答案
您可以在 shouldChangeTextInRange
方法中使用 textField.tag
。
将标签添加到相同 viewcontroller
的 textField
。并将该标记用于 shouldChangeTextInRange
方法。
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let currentText:NSString = storyView.text
let updatedText = currentText.stringByReplacingCharactersInRange(range, withString:text)
if updatedText.isEmpty {
if (textField.tag==0)//
{
storyView.text = "Write out your story here!" // stuff
}
else if(textField.tag==1)//
{
storyView.text = "Example 2 "// stuff
}
storyView.textColor = UIColor.lightGrayColor()
storyView.selectedTextRange = storyView.textRangeFromPosition(storyView.beginningOfDocument, toPosition: storyView.beginningOfDocument)
return false
}else if storyView.textColor == UIColor.lightGrayColor() && !text.isEmpty {
storyView.text = nil
storyView.textColor = UIColor.blackColor()
}
return true
}
func textViewDidChangeSelection(storyView: UITextView) {
if self.view.window != nil {
if storyView.textColor == UIColor.lightGrayColor() {
storyView.selectedTextRange = storyView.textRangeFromPosition(storyView.beginningOfDocument, toPosition: storyView.beginningOfDocument)
}
}
}
也许它会对你有所帮助。
关于ios - 多个 UITextView 占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35858891/