セルをタップすると伸び縮みする機能を実装したいのですが、
・セルに色が反映されない
・セルをタップしても伸び縮みしない
という問題に直面しています。
↓
カスタムセルを用いているので、ViewControllerのviewDidLoadでtableViewに登録しているはずなのにです。
delegata,datasourceに必要なtableViewのメソッドは全て記述してるか確認しましたが、どこも異常はありませんでした。
下記の記事のサンプルコードと同じに書いたのですが、ダメでした。
↓
Qiita そのまま使える!iOSアプリを作るためのswiftサンプル集
同じコードなのに動作しないのは、Swift4から仕様が変わったからでしょうか?
Qiitaの記事は最終更新日が比較的新しいので、コード的にも今の環境に適していると思うのですが、そうでなければ僕のコードが間違っているなのでしょうが、どこが間違いかわかりません。
どうかダメなのか指摘していただきたいです。
よろしくお願いします。
Swift
1import UIKit 2 3class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource { 4 5 6 @IBOutlet weak var tableView: UITableView! 7 8 private let dataSource: [UIColor] = [.red, .green, .blue, .cyan, .yellow, .magenta] 9 10 override func viewDidLoad() { 11 super.viewDidLoad() 12 13 //カスタムセルを登録する 14 tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "cell") 15 16 } 17 18 func numberOfSections(in tableView: UITableView) -> Int { 19 return 1 20 } 21 22 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 23 return dataSource.count 24 } 25 26 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 27 28 //gurad文でカスタムセルを読み込み、無理ならUITableViewCell()を返す 29 guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TableViewCell else { return UITableViewCell() } 30 31 cell.backgroundColor = dataSource[indexPath.row] 32 33 return cell 34 35 } 36 37 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 38 39 // 40 guard let cell = tableView.cellForRow(at: indexPath) as? TableViewCell else { return } 41 42 //??? 43 tableView.beginUpdates() 44 // 45 cell.flexible() 46 //??? 47 tableView.endUpdates() 48 49 } 50 51 52} 53 54
Swift
1import UIKit 2 3class TableViewCell: UITableViewCell { 4 5 //ConstraintをOutletで紐付け 6 @IBOutlet weak var cellHeight: NSLayoutConstraint! 7 8 override func awakeFromNib() { 9 super.awakeFromNib() 10 // Initialization code 11 } 12 13 override func setSelected(_ selected: Bool, animated: Bool) { 14 super.setSelected(selected, animated: animated) 15 16 // Configure the view for the selected state 17 } 18 19 func flexible() { 20 //セルの高さ(constraints)を変更する 21 //44なら100,44でないなら44 22 cellHeight.constant = cellHeight.constant == 44 ? 100 : 44 23 } 24 25} 26
※追記
ご回答通りに記述してもだめだったので、
Swift
1func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 2 3 //gurad文でカスタムセルを読み込み、無理ならUITableViewCell()を返す 4 guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TableViewCell else { return UITableViewCell() } 5 6// cell.backgroundColor = dataSource[indexPath.row] 7 cell.contentView.backgroundColor = dataSource[indexPath.row] 8 9 return cell 10 11 }
と書きましたが、だめでした。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/04 05:32