UITableView : cellの追加(セルの名前設定も)と削除

はじめに

cellの追加と削除についてアウトプット
自分用.memo
このブログ横幅狭い

実行環境

  • swift 4.0 (多分)
  • Xcode : 10.1

注意

qiita.com

qiita.com からの引用です

ソースコード全体

ソースコード

import UIKit

class ListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var tableView: UITableView!
    
    // 項目
    var data = [String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        // テーブルビューのdataSourceとdelegateを設定
        tableView.dataSource = self
        tableView.delegate = self
    }
  
    //セルの編集許可
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool
    {
        return true
    }
    
    //スワイプしたセルを削除
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete {
            data.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath as IndexPath], with: UITableView.RowAnimation.automatic)
        }
    }
    
    // cellの追加
    @IBAction func tapAdd(_ sender: UIBarButtonItem) {
        let alert: UIAlertController = UIAlertController(title: "セルの追加",
                                                         message: "追加する項目を入力してください",
                                                         preferredStyle: UIAlertController.Style.alert)
        alert.addTextField(configurationHandler: nil)
        let okAction = UIAlertAction(title: "OK",
                                     style: UIAlertAction.Style.default,
                                     handler:{
                                        (action: UIAlertAction) -> Void in
                                        self.data.insert(alert.textFields!.first!.text!, at: 0)
                                        // <重要>
                                        self.tableView.beginUpdates()
                                        self.tableView.insertRows(at: [IndexPath(row: 0, section: 0)],
                                                                  with: .automatic)
                                        self.tableView.endUpdates()
        })
        let cancelAction = UIAlertAction(title: "キャンセル",
                                         style: UIAlertAction.Style.cancel,
                                         handler: nil)
        alert.addAction(okAction)
        alert.addAction(cancelAction)
        self.present(alert, animated: true, completion: nil)
    }

    // 生成するセルの数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       
        return self.data.count
    }
    
    // セルの内容を知らせるメソッド
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = self.data[indexPath.row]
        
        return cell
    }
    
    // メモリ警告
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

アウトプット

セルの編集許可

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool
    {
        return true
    }

セルの削除にはこれが必要

スワイプしたセルを削除

   func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete {
            data.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath as IndexPath], with: UITableView.RowAnimation.automatic)
        }
    }

スワイプされたらこの関数が呼ばれる

ifの所のEditingStyleは列挙体。commandクリックで中身が

  • none
  • delete
  • insert

であることが分かる。
スワイプされた時に引数でeditingStyleを受け取り、deleteなら以下を実行

data.remove(at: indexPath.row) で配列の中身を削除した後
tableView.delete() でセルを削除する。

  • asはアップキャスト
  • with:はアニメーションの方式を指定
  • RowAnimationは列挙体でcommandクリックで

RowAnimation

 public enum RowAnimation : Int {

        
        case fade

        case right // slide in from right (or out to right)

        case left

        case top

        case bottom

        case none // available in iOS 3.0

        case middle // available in iOS 3.2.  attempts to keep cell centered in the space it will/did occupy

        case automatic // available in iOS 5.0.  chooses an appropriate animation style for you
    } 

と分かる。

cellの追加

// cellの追加
    @IBAction func tapAdd(_ sender: UIBarButtonItem) {
        let alert: UIAlertController = UIAlertController(title: "セルを追加",
                                                         message: "追加する項目を入力してください",
                                                         preferredStyle: UIAlertController.Style.alert)
        alert.addTextField(configurationHandler: nil)
        let okAction = UIAlertAction(title: "OK",
                                     style: UIAlertAction.Style.default,
                                     handler:{
                                        (action: UIAlertAction) -> Void in
                                        self.data.insert(alert.textFields!.first!.text!, at: 0)
                                        // <重要>
                                        self.tableView.beginUpdates()
                                        self.tableView.insertRows(at: [IndexPath(row: 0, section: 0)],
                                                                  with: .automatic)
                                        self.tableView.endUpdates()
        })
        let cancelAction = UIAlertAction(title: "キャンセル",
                                         style: UIAlertAction.Style.cancel,
                                         handler: nil)
        alert.addAction(okAction)
        alert.addAction(cancelAction)
        self.present(alert, animated: true, completion: nil)
    }

(ライブラリでItemをtableViewに置いてoutlet接続後(tapAdd)の話)

  • UIAlertController.Style.alertiPhoneの充電が20%になった時に出てくるあれ。

  • UIAlertController.Style.actionSheetは下の方に出てくるやつ。

  • alert.addTextField(configurationHandler: nil) はテキスト入力ボックスの追加

UIAlertAction(title: "OK",
                        style: UIAlertAction.Style.default,
                        handler:{})

はOKボタンの設置&OKを押した時のアクションをhandler以下に記述(クロージャ)。

UIAlertAction.Style

extension UIAlertAction {

    
    @available(iOS 8.0, *)
    public enum Style : Int {

        
        case `default` // titleが青文字

        case cancel     // cancelの時に使う

        case destructive   // titleが赤文字
    }
}

  • 入力したテキストは
self.data.insert(alert.textFields!.first!.text!, at: 0)

で拾える。

  • insertRows() (セルの挿入)をするには、
    self.tableView.beginUpdates()
    self.tableView.endUpdates()
    で挟まないといけない。
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(row: 0, section: 0)],with: .automatic)
self.tableView.endUpdates()
  • キャンセル時は何もしないので handler:nil
let cancelAction = UIAlertAction(title: "キャンセル",
                                         style: UIAlertAction.Style.cancel,
                                         handler: nil)
  • UIAlertに表示する。
alert.addAction(okAction)
alert.addAction(cancelAction)
  • モーダルビュー登場。
self.present(alert, animated: true, completion: nil)



アウトプット終わり!(疲れた)

参考

qiita.com

qiita.com