【Swift】TableViewでセルの伸び縮みを再現してみた

 

 

解説

 

 ・セルをタップすると、そのセルが縦に拡大する(伸びる)

・1番下のセルを押すと、なぜかそれよりも下の全てのセルも伸び縮みしてしまう

(原因はわかりません。)

・セルをタップした時に表示される色を消すために、tableView.deselectRow、を記述

 

ストーリーボード

 

f:id:nekokichi_yos2:20181011145653p:plain

f:id:nekokichi_yos2:20181011145655p:plain

 

ソースコード1

 

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    
    @IBOutlet weak var tableView: UITableView!
    
    let dataSource: [UIColor] = [.red, .green, .blue, .cyan, .yellow]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        //カスタムセルをtableViewに登録
        tableView.register(UINib(nibName: "CustomCell",
                                 bundle: nil), forCellReuseIdentifier: "CustomCell")
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell",
                                                 for: indexPath) as! CustomCell
        
        //カスタムセル - contentView - View(subview) - first?(1つ目の)
        //CustomCell.xibでは、contentViewの上にViewが置かれている
        //※cell.backgroundColor = ... はダメだった
        cell.contentView.subviews.first?.backgroundColor = dataSource[indexPath.row]
        
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let cell = tableView.cellForRow(at: indexPath) as! CustomCell
        
        tableView.deselectRow(at: indexPath, animated: false)
        
        //セルの伸び縮みアニメーションには、下記が推奨されている
        //beginUpdates(),
        //ここにコードを書く
        //endUpdates()
        tableView.beginUpdates()
        
        //セルの高さを変更する
        cell.cellheight()
        
        tableView.endUpdates()
        
    }

}

 

ソースコード2

 

import UIKit

class CustomCell: UITableViewCell {
    
    @IBOutlet weak var cellHeight: NSLayoutConstraint!
    
    //セルの高さを変更する
    func cellheight() {
        //heightのlayerに条件式で代入
        //44ですか? Yes/100、No/44
        cellHeight.constant = cellHeight.constant == 44 ? 100 : 44
    }
    
}