【问题标题】:showing action sheet in the custom cell in Swift在 Swift 的自定义单元格中显示操作表
【发布时间】:2015-09-25 14:00:46
【问题描述】:

我有一个自定义单元格,其中包含一个按钮,我想在按下按钮时显示一个操作表,但是正如你所知,UITableViewCell 没有方法“presentViewController”,所以我应该怎么做?

【问题讨论】:

    标签: swift uitableview uialertcontroller


    【解决方案1】:

    在您的自定义单元格的 swift 文件中,编写一个由您的 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() 方法。

    在 cellForRowAtIndexPath dataSource 方法中创建单元格时,将您的 viewContoller 指定为自定义单元格的委托。

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

    【讨论】:

    • 有没有教程解释你在说什么?我知道协议,但我不知道如何使用它。
    • 可能有一些教程,但我编辑了答案。我希望它会有所帮助
    【解决方案2】:

    你会这样做:

    1. 在您的客户UITableViewCell 上创建一个协议,比如MyTableViewCellDelegate
    2. 在您的协议中添加方法cellButtonTapped
    3. 使您的视图控制器(使用这些单元格)符合MyTableViewCellDelegate,即在头文件中添加<MyTableViewCellDelegate>
    4. 在视图控制器的cellForRowAtIndexPath: 方法中,初始化单元格时,将self 设置为委托。
    5. 在您的自定义表格视图单元格类中,当点击按钮时,将控件移交给它的委托,即您的视图控制器。
    6. 在您的视图控制器中实现方法cellButtonTapped 并根据需要显示操作表。

    【讨论】:

      猜你喜欢
      • 2014-08-05
      • 2019-08-21
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      相关资源
      最近更新 更多