单击另一个 UITextView 时结束编辑
End editing when clicking on another UITextView
我有一个带有多个自定义单元格的 UITableViewController,每个自定义单元格都包含一个 UITextView。我希望这样,如果用户正在编辑单元格 A 然后单击单元格 B,则单元格 A 结束编辑但单元格 B 不会 开始编辑。
现在我有以下手势识别器,当在 tableView 外部单击时结束单元格的编辑:
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissKeyboard)];
[tap setCancelsTouchesInView:NO];
[self.view addGestureRecognizer:tap];
但是当点击另一个 UITextView 时,此 textview 会在之后调用 shouldBeginEditing
,因此会被忽略。
我尝试使用 textViewShouldBeginEditing
/ textViewShouldEndEditing
函数但没有成功。我不知道我是应该追求这个方向还是创建另一个具有自定义关联操作的手势识别器?
您需要设置很多东西才能使其正常工作。
您的所有 UITextField
都需要设置委托。您需要跟踪 UITextField
当前是否正在编辑。如果是这样,您需要调用 resignFirstResponder
否则您将让新点击的 UITextField
开始编辑。
代码看起来像这样。
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool
{
if self.currentTextField == nil
{
self.currentTextField = textField
return true
}
else
{
self.currentTextField!.resignFirstResponder()
self.currentTextField = nil
}
}
我有一个带有多个自定义单元格的 UITableViewController,每个自定义单元格都包含一个 UITextView。我希望这样,如果用户正在编辑单元格 A 然后单击单元格 B,则单元格 A 结束编辑但单元格 B 不会 开始编辑。
现在我有以下手势识别器,当在 tableView 外部单击时结束单元格的编辑:
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissKeyboard)];
[tap setCancelsTouchesInView:NO];
[self.view addGestureRecognizer:tap];
但是当点击另一个 UITextView 时,此 textview 会在之后调用 shouldBeginEditing
,因此会被忽略。
我尝试使用 textViewShouldBeginEditing
/ textViewShouldEndEditing
函数但没有成功。我不知道我是应该追求这个方向还是创建另一个具有自定义关联操作的手势识别器?
您需要设置很多东西才能使其正常工作。
您的所有 UITextField
都需要设置委托。您需要跟踪 UITextField
当前是否正在编辑。如果是这样,您需要调用 resignFirstResponder
否则您将让新点击的 UITextField
开始编辑。
代码看起来像这样。
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool
{
if self.currentTextField == nil
{
self.currentTextField = textField
return true
}
else
{
self.currentTextField!.resignFirstResponder()
self.currentTextField = nil
}
}