答案 0 :(得分:2)
可以通过查找换行符textViewDidChange
在"\n"
中执行此操作。
否则,更好的办法是通过检查func textView(UITextView, shouldChangeTextIn: NSRange, replacementText: String)
replacementText == "\n"
示例:
func textView(UITextView, shouldChangeTextIn: NSRange, replacementText: String){
if replacementText == "\n"{
// do your stuff here
// return false here, if you want to disable user from adding newline
}
// otherwise, it will return true and the text will be replaced
return true
}
答案 1 :(得分:1)
我刚试过这个。似乎满足您的要求:
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var myTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
myTextView.delegate = self
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
{
if(text == "\n")
{
view.endEditing(true)
return false
}
else
{
return true
}
}
}
答案 2 :(得分:-1)
使用 textFieldShouldReturn:方法
O(N*log(N))