showing action sheet in the custom cell in Swift

馋奶兔 提交于 2020-01-14 03:46:10

问题


I have a custom cell that contains a button inside it, I want to show an action sheet when the button is pressed, but as u know , UITableViewCell is doesn't have the method "presentViewController", so what should I do?


回答1:


In your custom cell's swift file, write a protocol to be conformed by your viewContoller,

// your custom cell's swift file

protocol CustomCellDelegate {
    func showActionSheet()
}

class CustomTableViewCell : UITableViewCell {
    var delegate: CustomCellDelegate?

    // This is the method you need to call when button is tapped.
    @IBAction func buttonTapped() {

        // When the button is pressed, buttonTapped method will send message to cell's delegate to call showActionSheet method.
        if let delegate = self.delegate {
            delegate.showActionSheet()
        }
    }
}

// Your tableViewController
// it should conform the protocol CustomCellDelegate

class MyTableViewController : UITableViewController, CustomCellDelegate {

    // other code

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("CustomCellReuseIdentifier", forIndexPath: indexPath)

        // configure cell

        cell.delegate = self        

        return cell
    }

    // implement delegate method
    func showActionSheet() {

        // show action sheet

    }
}

Make sure your view controller conforms CustomCellDelegate protocol and implements showActionSheet() method.

Assign your viewContoller as delegate of the custom cell when creating your cells in cellForRowAtIndexPath dataSource method.

You can present your new view controller from the showActionSheet method in viewController.




回答2:


This is how you would do this:

  1. Create a protocol on your customer UITableViewCell say MyTableViewCellDelegate.
  2. Add a method cellButtonTapped in your protocol.
  3. Conform your view controller (that uses these cells) to MyTableViewCellDelegate i.e. in the header file add <MyTableViewCellDelegate>.
  4. In your view controller's cellForRowAtIndexPath: method, when initializing cell, set self as delegate.
  5. In your custom table view cell class, when button is tapped, handover the control to its delegate which is your view controller.
  6. Implement method cellButtonTapped in your view controller and present action sheet as you like.


来源:https://stackoverflow.com/questions/32783933/showing-action-sheet-in-the-custom-cell-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!