为避免此问题,您可以采取的措施是禁用表视图用户交互,并在推送到第二个视图控制器后重新启用它。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// add this:
tableView.isUserInteractionEnabled = false
let message = messages[indexPath.row]
guard let chatPartnerId = message.chatPartnerId() else {return}
let ref = Database.database().reference().child("users").child(chatPartnerId)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: AnyObject] else {
return
}
let user = ChatUser(dictionary: dictionary)
user.id = chatPartnerId
self.showChatControllerForUser(user)
}, withCancel: nil)
}
func showChatControllerForUser(_ user: ChatUser) {
let chatLogController = ChatLogController(collectionViewLayout: UICollectionViewFlowLayout())
chatLogController.chatUser = user
// edit this:
navigationController?.pushViewController(chatLogController, animated: true)
navigationController?.pushViewController(chatLogController, animated: true, completion: {
self.tableView.isUserInteractionEnabled = true
})
}
默认情况下,pushViewController(_:animated:) https://developer.apple.com/documentation/uikit/uinavigationcontroller/1621887-pushviewcontroller没有完成处理程序,因此作为解决方法,我们可以添加以下扩展来实现它:
extension UINavigationController {
public func pushViewController(
_ viewController: UIViewController,
animated: Bool,
completion: @escaping () -> Void)
{
pushViewController(viewController, animated: animated)
guard animated, let coordinator = transitionCoordinator else {
DispatchQueue.main.async { completion() }
return
}
coordinator.animate(alongsideTransition: nil) { _ in completion() }
}
}
Cited from: https://stackoverflow.com/a/33767837/5501940 https://stackoverflow.com/a/33767837/5501940