[swift] カスタムtableViewCellのActionでAlertを表示させる
カスタムtableViewCellのActionでAlertを表示させる
カスタムtableViewCellのActionでAlertを表示させるには、カスタムtableViewCell.swift上でalertの設定を行うが、Alertを表示させる
self.presentViewController(self.alert, animated: true, completion: nil)
のpresentViewControllerはviewControllerしか持っていないメソッドなのでエラーになる
以下のようにカスタムtableViewCell.swiftのコードを書き換える
import UIKit class customCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var button:UIButton! var delegate: UIViewController? //必要 var alert:UIAlertController! @IBAction func didPushedButton(){ showAlert() } func showAlert(){ alert = UIAlertController(title:"Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert) let cancelAction:UIAlertAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler:{ action in }) let OKAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{ (action:UIAlertAction!) -> Void in [実行メソッド] }) alert.addAction(cancelAction) alert.addAction(OKAction) delegate!.presentViewController(alert, animated: true, completion: nil) //必要 } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } /// 画像・タイトル・説明文を設定するメソッド func setCell(titleText: String) { titleLabel.text = titleText } }
あとはtableViewContorllerにも以下のコードを追加
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("customCell") as! customCell cell.delegate = self //必要 cell.setCell("title") return cell }