【发布时间】:2015-09-25 14:00:46
【问题描述】:
我有一个自定义单元格,其中包含一个按钮,我想在按下按钮时显示一个操作表,但是正如你所知,UITableViewCell 没有方法“presentViewController”,所以我应该怎么做?
【问题讨论】:
标签: swift uitableview uialertcontroller
我有一个自定义单元格,其中包含一个按钮,我想在按下按钮时显示一个操作表,但是正如你所知,UITableViewCell 没有方法“presentViewController”,所以我应该怎么做?
【问题讨论】:
标签: swift uitableview uialertcontroller
在您的自定义单元格的 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 方法展示您的新视图控制器。
【讨论】:
你会这样做:
UITableViewCell 上创建一个协议,比如MyTableViewCellDelegate。cellButtonTapped。MyTableViewCellDelegate,即在头文件中添加<MyTableViewCellDelegate>。cellForRowAtIndexPath: 方法中,初始化单元格时,将self 设置为委托。cellButtonTapped 并根据需要显示操作表。【讨论】: