cellを削除したい!!
初学者です。
TestAppを制作しています。
オプションボタンを作って、Twitterのように削除したいと思って、実装を試みましたが、上手くいきません。
発生している問題
Customcellをオプションボタンで削除したいと思っています。
が、
swift
1self.itemArray.remove(at: indexPathRow) 2self.tableView.reloadData()
しても消えてくれません。
なぜ消えないのか、また何が足りないのかも現状わからない状態です。
補足情報
コード全文を載せておきます。
swift.TableViewCell
1 2import UIKit 3 4protocol TableViewCellDelegate { 5 func deleteButton(indexPathRow: Int) 6} 7 8class TableViewCell: UITableViewCell { 9 10 var delegate: TableViewCellDelegate? 11 var indexPathRow = 0 12 13 @IBAction func deleteButton(_ sender: Any) { 14 delegate?.deleteButton(indexPathRow: indexPathRow) 15 } 16 override func awakeFromNib() { 17 super.awakeFromNib() 18 // Initialization code 19 } 20 21 override func setSelected(_ selected: Bool, animated: Bool) { 22 super.setSelected(selected, animated: animated) 23 24 // Configure the view for the selected state 25 } 26 27}
swift.ViewController
1import UIKit 2 3class ViewController: UIViewController { 4 5 var itemArray = ["cell 1","cell 2","cell 3"] 6 7 @IBOutlet weak var tableView: UITableView! 8 9 10 override func viewDidLoad() { 11 super.viewDidLoad() 12 let tableView = UITableView(frame: self.view.bounds, style: .plain) 13 //tableViewの設定を記述 14 tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "customCell") 15 tableView.delegate = self 16 tableView.dataSource = self 17 view.addSubview(tableView) 18 } 19} 20 21extension ViewController: UITableViewDelegate,UITableViewDataSource { 22 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 23 itemArray.count 24 } 25 26 27 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 28 //tableViewの内容を指定 29 let cell = tableView.dequeueReusableCell(withIdentifier: "customCell",for: indexPath) as! TableViewCell 30 //忘れやすいので注意 31 cell.indexPathRow = indexPath.row 32 cell.delegate = self 33 return cell 34 } 35} 36extension ViewController: TableViewCellDelegate { 37 38 func deleteButton(indexPathRow: Int) { 39 let alert: UIAlertController = UIAlertController(title: "注意", message: "削除してもいいですか?", preferredStyle: .alert) 40 let canselAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: .cancel) { (UIAlertAction) in 41 print("キャンセル") 42 } 43 let okAction: UIAlertAction = UIAlertAction(title: "削除", style: .destructive) { (UIAlertAction) in 44 45 self.itemArray.remove(at: indexPathRow) 46 //アニメーションを追加したいが、設定がよくわからない。 47 //self.tableView.deleteRows(at: indexPathRow, with: .automatic) 48 49 self.tableView.reloadData() 50 51 52 print(self.itemArray) 53 } 54 alert.addAction(okAction) 55 alert.addAction(canselAction) 56 present(alert, animated: true, completion: nil) 57 } 58}
以下の画像はCustomCellの表示内容です。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/02/25 03:23