我有一个UITextView,它位于静态表格视图中,如果用户触摸文本视图之外的其他区域,我想要移除键盘。
通常情况下,我可以使用以下代码行来移除键盘,但是我不知道为什么,在TextView中添加占位符后,它不起作用。我怀疑这是因为它位于静态表格视图中。
extension CheckinDetailTVC {
// to remove keyboard if we touch other area
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(false)
}
}
我也尝试了stackoverflow上的另一个解决方案,但它们都没有起作用,例如添加手势识别器
override func viewDidLoad() {
super.viewDidLoad()
let tapGestureReconizer = UITapGestureRecognizer(target: self, action: "tap:")
view.addGestureRecognizer(tapGestureReconizer)
}
func tap(sender: UITapGestureRecognizer) {
view.endEditing(true)
}
或者在TextViewDelegate中添加功能,但它也不起作用。
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
textView.resignFirstResponder()
}
return true
}
这是我的用户界面截图:
这是我在视图控制器中使用的简化代码:
class CheckinDetailTVC: UITableViewController {
@IBOutlet weak var noteTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// to put placeholder for UITextView
noteTextView.delegate = self
noteTextView.text = "Write your note in here ..."
noteTextView.textColor = UIColor.lightGray
noteTextView.becomeFirstResponder()
noteTextView.selectedTextRange = noteTextView.textRange(from: noteTextView.beginningOfDocument, to: noteTextView.beginningOfDocument)
}
}
extension CheckinDetailTVC : UITextViewDelegate {
// add placeholder for textView
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let currentText:String = textView.text
let updatedText = (currentText as NSString).replacingCharacters(in: range, with: text)
if updatedText.isEmpty {
textView.text = "Write your note in here ..."
textView.textColor = UIColor.lightGray
textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
return false
}
else if textView.textColor == UIColor.lightGray && !text.isEmpty {
textView.text = nil
textView.textColor = UIColor.black
}
return true
}
func textViewDidChangeSelection(_ textView: UITextView) {
if self.view.window != nil {
if textView.textColor == UIColor.lightGray {
textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
}
}
}
}
extension CheckinDetailTVC {
// usually i can use this code to remove keyboard if we touch other area
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(false)
}
}
这里出了什么问题?
func tap(sender: UITapGestureRecognizer) {
中使用noteTextView.resignFirstResponder()
吗? - Anbu.Karthik