現在iosアプリを制作しているのですが、autolayoutをtableViewのセルによって動的に変更したく、SnapKitを使ってコードから設定しています。
autolayout自体はきちんと設定できているのですが、セルの高さが可変にならず、セル内の要素がセルからはみだしてしまいます。
tableViewの設定は下記です。
swift
1import UIKit 2 3class ViewController: UIViewController { 4 @IBOutlet var tableView: UITableView! 5 var datas = [true, false, true, false, false] 6 7 override func viewDidLoad() { 8 super.viewDidLoad() 9 tableView.delegate = self 10 tableView.dataSource = self 11 let nib = UINib(nibName: "TableViewCell", bundle: nil) 12 tableView.register(nib, forCellReuseIdentifier: "Cell") 13 tableView.estimatedRowHeight = 350 14 tableView.rowHeight = UITableViewAutomaticDimension 15 16 } 17 18 private func createData() -> [Bool]{ 19 let datas = [true, false, true, false, false] 20 return datas 21 } 22} 23 24extension ViewController: UITableViewDelegate, UITableViewDataSource { 25 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 26 return datas.count 27 } 28 29 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 30 var cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell 31 print(datas[indexPath.row]) 32 cell.data = datas[indexPath.row] 33 return cell 34 } 35}
セル内でのautolayoutの設定は下記です.
swift
1 var data: Bool? { 2 didSet{ 3 guard let data = data else { return } 4 self.setUpUI(data: data) 5 } 6 } 7 8 private func setUpUI(data:Bool){ 9 if data == true { 10 label.backgroundColor = .blue 11 label.snp.makeConstraints({ (make) -> Void in 12 make.top.equalTo(10) 13 make.bottom.equalTo(10) 14 }) 15 }else{ 16 label.backgroundColor = .red 17 label.snp.makeConstraints({ (make) -> Void in 18 make.top.equalTo(100) 19 make.bottom.equalTo(100) 20 }) 21 } 22 }
tableViewの設定を上記のまま、autoLayoutをstoryBoardから設定するときちんとセルの高さが可変になります。
どなたか原因のわかる方、ご教授よろしくおねがいいたします。
回答2件
あなたの回答
tips
プレビュー