0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UITableViewCellクラスを用いてcellを規定する

0
Last updated at Posted at 2021-03-10

UITableViewCellクラスを用いてcellを規定。
cellがもつプロパティ毎にデータを管理する必要がある。

import UIKit

struct Item {
    var title:String
    var image: UIImage?
    var titleIsHidden: Bool
    var buttonTitle: String {
        switch titleIsHidden {
            case true:
                return "表示"
            case false:
                return "非表示"
        }
    }
}


class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    private var items = Array<Item>(repeating: Item(title: "text", image: UIImage(named: "bunny"), titleIsHidden: false), count: 20)


    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
    }


    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        80
    }


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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Reuse or create a cell.
        let cell = tableView.dequeueReusableCell(withIdentifier: "basicStyle", for: indexPath) as! BasicStyle

        cell.configure(
            item: items[indexPath.row],
            didTapHideButton: { [weak self] in
                self?.items[indexPath.row].titleIsHidden.toggle()
                self?.tableView.reloadRows(at: [indexPath], with: .automatic)
            }
        )
        return cell
    }
}

class BasicStyle: UITableViewCell {
    @IBOutlet private weak var hideButton: UIButton!

    private var didTapHideButtonHandler: () -> Void = {}

    func configure(item: Item, didTapHideButton: @escaping () -> Void) {
        textLabel?.text = item.title
        imageView?.image = item.image
        textLabel?.isHidden = item.titleIsHidden
        hideButton.setTitle(item.buttonTitle, for: .normal)
        didTapHideButtonHandler = didTapHideButton
    }

    @IBAction func didTapHideButton(_ sender: Any) {
        didTapHideButtonHandler()
    }
}

Videotogif.gif

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?