首页 > 解决方案 > iOS 13 UIContextualAction 完成触发意外的键盘关闭

问题描述

我有一个UITableView带有可交换UIContextualActions以删除或重命名(编辑)单个单元格的文本字段的单元格。

由于我切换到Swift 5 / iOS 13,在这些单元格上触发重命名UIContextualAction会导致键盘启动并在用户有机会键入之前立即关闭。不仅键盘消失了,我试图编辑的特定单元格也变得完全空了,并且生成了以下警告:

[Snapshotting] Snapshotting a view (0x10c90a470, _UIReplicantView) that has not been rendered at least once requires afterScreenUpdates:YES.

下面是重命名的代码UIContextualAction

let actionRename = UIContextualAction(style: .normal, title: "") { (action, view, completionHandler) in

      let cell = self.tableLayers.cellForRow(at: indexPath) as! LayerUITableViewCell
      cell.layerTitle.isEnabled = true // enable UITextField editing
      cell.layerTitle.becomeFirstResponder() // launch keyboard
      cell.layerTitle.selectedTextRange = cell.layerTitle.textRange(from: (cell.layerTitle.beginningOfDocument), to: (cell.layerTitle.endOfDocument)) // select all text
      completionHandler(true)

} // end of let actionRename

我猜 UIContextual 动作的动画以某种方式触发了键盘的resignFirstResponder.

总而言之,在 之前swift 5/iOS 13,事件的顺序是这样的:

  1. 用户向左/向右滑动单元格
  2. 用户点击 UIContextual 按钮
  3. 单元格返回中心
  4. 文本被选中
  5. 键盘启动
  6. 用户类型,点击返回
  7. 键盘resignFirstResponder

而我在迁移后看到的行为如下所示:

  1. 用户向左/向右滑动单元格
  2. 用户点击 UIContextual 按钮
  3. 文本被选中
  4. 键盘启动
  5. 单元格返回中心(以某种方式触发resignFirstResponder
  6. 键盘resignFirstResponder

更新 2019/10/02

我已经确认是单元格动画导致键盘过早关闭。如果我在 completionHandler 之后引入延迟如下:

let actionRename = UIContextualAction(style: .normal, title: "") { (action, view, completionHandler) in

      completionHandler(true)
      self.perform(#selector(self.layerRenameDos), with: nil, afterDelay: 1.0)   
      // layerRenameDos has the editing/firstResponder code from above

    } // end of let actionRename

有了这个改变,单元格动画回到中心,键盘启动,我可以打字了。然而,这显然是一个 hacky 解决方法。任何建议,将不胜感激

标签: uitableviewios13swift5resignfirstresponderuicontextualaction

解决方案


我认为这是一个更好的解决方案。请确保在下一个运行循环中执行您的代码。

CATransaction.begin()
CATransaction.setCompletionBlock {
   DispatchQueue.main.async {
     //your code on the next runloop after the animation has finished
   }
}
complitionHandler(true)
// or tableView.setEditing(false, animated: true)
CATransaction.commit()

推荐阅读