在 Swift 中的自定义单元格中显示操作表 [英] showing action sheet in the custom cell in Swift

查看:28
本文介绍了在 Swift 中的自定义单元格中显示操作表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义单元格,其中包含一个按钮,我想在按下按钮时显示一个操作表,但正如您所知,UITableViewCell 没有方法presentViewController",那我该怎么办?

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?

推荐答案

在自定义单元格的 swift 文件中,编写一个协议以供您的 viewContoller 遵守,

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

    }
}

确保您的视图控制器符合 CustomCellDelegate 协议并实现 showActionSheet() 方法.

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

在 cellForRowAtIndexPath 数据源方法中创建单元格时,将您的 viewContoller 指定为自定义单元格的委托.

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

您可以通过 viewController 中的 showActionSheet 方法展示您的新视图控制器.

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

这篇关于在 Swift 中的自定义单元格中显示操作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆