LoginSignup
0
1

More than 3 years have passed since last update.

テーブルビューにセルを追加する【Swift】

Last updated at Posted at 2021-03-27

Swift学習2日目、自分用の備忘録です。

テキストフィールドにテキストを入力後リターンを押すとテーブルビューにセルを追加するコード。

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var textField: UITextField!
    var textArray = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        textField.delegate = self
    }

    // 画面が表示されるたびに呼ばれる
    override func viewWillAppear(_ animated: Bool) {
        // ナビゲーションコントローラーを非表示
        navigationController?.isNavigationBarHidden = true
    }

    // 1. セルのセクション数を決めるメソッド
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    // 2. セルの数を決めるメソッド
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return textArray.count
    }

    // 3. セルを構築する際に呼ばれるメソッド
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // /////////////////////////////////////////////////////////////
        // 事前にTable View CellのIdentifierをCellに設定しておく
        // /////////////////////////////////////////////////////////////
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = textArray[indexPath.row] // テキストを設定
        cell.imageView!.image = UIImage(named: "checkImage") // 画像を設定
        cell.selectionStyle = .none // セルをクリックした時のハイライトをオフに

        return cell
    }

    // 4. セルの高さを決めるメソッド
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return view.frame.size.height / 6
    }


    // 5. セルがタップされた時の呼ばれるメソッド
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 画面遷移
        let nextVC = storyboard?.instantiateViewController(withIdentifier: "next") as! NextViewController
        nextVC.todoString = textArray[indexPath.row]
        navigationController?.pushViewController(nextVC, animated: true)
    }

    // リターンキーが押された時の処理
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.text == "" {
            return // テキストフィールドが空なら以降の処理は行わない
        }

        textArray.append(textField.text!) // textArrayにテキストを追加
        textField.resignFirstResponder() // キーボードを閉じる
        textField.text = "" // テキストフィールドを空に
        tableView.reloadData() // テーブルビューを更新
    }
}


セルのデザインを自由に設定する場合

  1. Table View CellのContent Viewにパーツ(ラベル、ボタンなど)を自由に配置
  2. パーツにtagを設定
  3. 以下のようにコードを実装
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView! // テーブルビューを紐付け
    @IBOutlet weak var textField: UITextField! // テキストフィールドを紐付け

    var textArray = [String]()
    var imageArray = ["1", "2", "3", "4", "5"]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }


    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return textArray.count
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 550 // セルの高さに合わせて設定
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        let imageView = cell.contentView.viewWithTag(1) as! UIImageView // タグ1をつけたImage View
        let label = cell.contentView.viewWithTag(2) as! UILabel // タグ2をつけたLabel

        imageView.image = UIImage(named: imageArray[indexPath.row]) // 画像を代入
        label.text =  textArray[indexPath.row] // テキストを代入

        return cell
    }



    @IBAction func tap(_ sender: Any) {

        textArray.append(textField.text!)

        if textArray.count > 5 || textField.text!.isEmpty == true {
            return // 以降の処理は行わない
        }

        textField.text = ""
        tableView.reloadData()
    }
}


0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1