我与 kabiroberai 走在同一条道路上寻找这个答案的解决方案,但采取了不同的方法,使用两个独立的协议,而不是一个可能被滥用的 Objective-C/NSObject 协议。这也避免了将协议方法设为可选。
首先,创建两个单独的协议以公开UITableView 和UITableViewCell 上的私有方法。我通过挖掘每个类的private headers 找到了这些。
@objc protocol UITableViewCellPrivate {
func setShowingDeleteConfirmation(arg1: Bool)
}
@objc protocol UITableViewPrivate {
func _endSwipeToDeleteRowDidDelete(arg1: Bool)
}
在cellForRowAtIndexPath 中,保留对要显示其编辑操作的单元格(或多个单元格)的引用:
class MyTableViewController: UITableViewController {
var cell: UITableViewCell?
// ...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
// ...
if indexPath.row == 1 {
self.cell = cell
}
return cell
}
}
现在,触发私有方法。我用performSelector:withObject:afterDelay,或者你可以用一个按钮。
override func viewDidLoad() {
super.viewDidLoad()
self.performSelector(#selector(showActionsForCell), withObject: nil, afterDelay: 2.0)
}
func showActionsForCell() {
if let cell = cell {
let cellPrivate = unsafeBitCast(cell, UITableViewCellPrivate.self)
let tableViewPrivate = unsafeBitCast(self.tableView, UITableViewPrivate.self)
// Dismiss any other edit actions that are open
tableViewPrivate._endSwipeToDeleteRowDidDelete(false)
// Open the edit actions for the selected cell
cellPrivate.setShowingDeleteConfirmation(true)
}
}
直接拨打unsafeBitCast 很危险。为安全起见,请检查您的 UITableView 和 UITableViewCell 是否响应这些选择器,或将这些功能设为可选。