Skip to content

Instantly share code, notes, and snippets.

@malonehedges
Created June 25, 2019 01:17
Show Gist options
  • Save malonehedges/226d279d98721a5e603b35b4bd97de81 to your computer and use it in GitHub Desktop.
Save malonehedges/226d279d98721a5e603b35b4bd97de81 to your computer and use it in GitHub Desktop.
auto-sizing cells with variable height content
import UIKit
import SnapKit
class TestVC: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 58
tableView.rowHeight = UITableView.automaticDimension
tableView.dataSource = self
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return MyCell()
}
}
class MyCell : UITableViewCell {
init() {
super.init(style: .default, reuseIdentifier: nil)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
let myView = MyView()
contentView.addSubview(myView)
myView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
}
class MyView: UIView {
lazy var artView: UIView = {
let artView = UIView()
artView.backgroundColor = .black
return artView
}()
lazy var textView: UIView = {
let textView = UIView()
textView.backgroundColor = .darkGray
return textView
}()
init() {
super.init(frame: .zero)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
addSubview(artView)
artView.snp.makeConstraints { make in
make.size.equalTo(48)
make.left.equalToSuperview().offset(16)
make.centerY.equalToSuperview()
make.top.greaterThanOrEqualToSuperview().inset(5)
make.bottom.lessThanOrEqualToSuperview().inset(5)
}
addSubview(textView)
textView.snp.makeConstraints { make in
make.left.equalTo(artView.snp.right).offset(12)
make.right.equalToSuperview().inset(16)
make.height.equalTo(20 + CGFloat.random(in: 0...56))
make.centerY.equalToSuperview()
make.top.greaterThanOrEqualToSuperview().inset(5)
make.bottom.lessThanOrEqualToSuperview().inset(5)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment