
[英]resignfirstresponder on a UITextView inside a UITableViewCell
[英]ResignFirstResponder for UITextView in UITableViewCell when scrolled out of screen
我有可编辑的自定义(笔尖)加载可重用的UITableViewCell
,其中包含UITextView
。 这些行是自动调整大小的。 我有一个问题,如果用户开始编辑UITextView
然后开始滚动焦点,则焦点(firstResponder)仍然保持不变,我认为这是一个问题,因为通常允许删除或重复使用屏幕单元格。 这会导致问题,因此该行仍保留在内存中,并在以后的错误位置显示。
我认为一个好的解决方案是在单元格resignFirstResponder
屏幕上时为UITextView
调用resignFirstResponder
。 但是在这种情况下似乎没有调用didEndDisplayingCell
。 我也尝试过prepareForReuse
,它既不被调用。
有任何想法吗?
public func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
{
if (tableView.indexPathsForVisibleRows?.indexOf(indexPath) == nil) {
if let noteCell = cell as? AgendaNotesTableViewCell {
noteCell.noteTextView.resignFirstResponder()
}
}
}
似乎对于所有单元格(除了当前为firstResponder的单元格)都可以正常工作。 我猜它一直保存在内存中,因此从不用于调用didEndDisplayingCell
在viewDidLoad
方法UITableview
UIGestureRecognizer
添加到UITableview
中,
UITapGestureRecognizer * gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeKeyboard)];
[self.tableView addGestureRecognizer:gesture];
使用其委托方法之一保留UITextView
引用
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
当点击表格视图时,手势识别器方法将调用,即
- (void)removeKeyboard {
// set resignFirstResponder to textview
}
我想出了一个解决方案。 可以,但是如果有人找到更好的,我会标记为正确。
我在视图控制器中添加了一个变量,以跟踪firstResponder UITextView
的当前indexPath。 每次我开始编辑UITextView
,都会在viewController中使用此方法设置此变量:
private var currentFirstResponderIndexPath:NSIndexPath? = nil
public func didSetFirstResponderIndexPath(indexPath:NSIndexPath?)
{
currentFirstResponderIndexPath = indexPath
}
在我的自定义UITableViewCell
:
//MARK: - UITextViewDelegate
public func textViewDidEndEditing(textView: UITextView)
{
//....
agendaViewController?.didSetFirstResponderIndexPath(nil)
}
public func textViewDidBeginEditing(textView: UITextView)
{
//...
agendaViewController?.didSetFirstResponderIndexPath(indexPath)
}
其中,议程视图控制器是指向视图控制器的弱指针。 这也可以是代表。
然后在滚动时检查当前的firstResponder是否不可见:
//MARK: - UIScrollViewDelegate
public func scrollViewDidScroll(scrollView: UIScrollView)
{
updateHelperAlphas()
if let indexPath = currentFirstResponderIndexPath {
let visibleCellIndexPaths = tableView.indexPathsForVisibleRows ?? []
let indexPathForCellWithFirstResponderIsOutOfScreen = !visibleCellIndexPaths.contains(indexPath)
if (indexPathForCellWithFirstResponderIsOutOfScreen) {
self.view.endEditing(true)
}
}
}
但是,此解决方案确实有一些缺点。 如果开始在表格视图的底部编辑一行,它将显示键盘并隐藏将退出第一响应者的单元格,该单元格将隐藏键盘et.c。 那里需要更多的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.