【发布时间】:2018-02-07 08:09:31
【问题描述】:
我有 UITextView 在静态表格视图中,如果用户触摸 textView 之外的其他区域
,我想移除键盘>通常我可以用这行代码来移除键盘,但我不知道为什么,在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)
}
}
这里出了什么问题?
【问题讨论】:
-
你试过
noteTextView.resignFirstResponder()方法里面的func tap(sender: UITapGestureRecognizer) { -
天哪,新手错误,我忘记将视图编辑为noteTextView。非常感谢 Anbu Karthik
标签: ios swift uitableview uitextview uitapgesturerecognizer