带有堆栈视图的CustomTableViewCell
class CustomTableViewCell: UITableViewCell {
let titleLbl = UILabel()
let stackView = UIStackView()
let imgView = UIImageView()
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLbl.translatesAutoresizingMaskIntoConstraints = false
addSubview(titleLbl)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 0
stackView.alignment = .fill
stackView.distribution = .fill
addSubview(stackView)
imgView.translatesAutoresizingMaskIntoConstraints = false
let imgViewHeight = imgView.heightAnchor.constraint(equalToConstant: 100)
imgViewHeight.priority = .defaultLow
imgViewHeight.isActive = true
imgView.addConstraint(imgViewHeight)
stackView.addArrangedSubview(imgView)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[titleLbl]|", options: [], metrics: nil, views: ["titleLbl":titleLbl,"stackView":stackView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[titleLbl(30)][stackView]|", options: [.alignAllLeading,.alignAllTrailing], metrics: nil, views: ["titleLbl":titleLbl,"stackView":stackView]))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
带有自动高度tableView的ViewController
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomCell")
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 130
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 15
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomTableViewCell
cell.titleLbl.text = "Row \(indexPath.row)"
// set cell.imgView.image
cell.imgView.isHidden = cell.imageView?.image == nil
return cell
}
}