Open UITableView edit action buttons programmatically

前端 未结 5 2017
忘掉有多难
忘掉有多难 2020-11-29 03:54

I have a UIPageViewController that have UITableViewControllers inside it, and the swipe left gestures are conflicted between the UIPageViewCo

5条回答
  •  囚心锁ツ
    2020-11-29 04:39

    I was on the same path as kabiroberai in finding a solution to this answer, but took a different approach with two separate protocols rather than one Objective-C/NSObject protocol that could potentially be misused. This also prevents having to make the protocol methods optional.

    First, create two separate protocols to expose the private methods on both the UITableView and UITableViewCell. I found these by digging through the private headers of each class.

    @objc protocol UITableViewCellPrivate {
        func setShowingDeleteConfirmation(arg1: Bool)
    }
    
    @objc protocol UITableViewPrivate {
        func _endSwipeToDeleteRowDidDelete(arg1: Bool)
    }
    

    In cellForRowAtIndexPath, keep a reference to the cell (or multiple cells) which you want to show the edit actions for:

    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
        }
    }
    

    Now, fire the private methods. I used performSelector:withObject:afterDelay, or you can use a button.

    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)
        }
    }
    

    Calling unsafeBitCast directly is dangerous. For safety, check if your UITableView and UITableViewCell respond to those selectors, or make the functions optional.

提交回复
热议问题