问题
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:
- Create a protocol on your customer
UITableViewCell
sayMyTableViewCellDelegate
. - Add a method
cellButtonTapped
in your protocol. - Conform your view controller (that uses these cells) to
MyTableViewCellDelegate
i.e. in the header file add<MyTableViewCellDelegate>
. - In your view controller's
cellForRowAtIndexPath:
method, when initializing cell, set self as delegate. - In your custom table view cell class, when button is tapped, handover the control to its delegate which is your view controller.
- 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