在设置自定义UITableViewCells高度时,需要考虑以下几个关键步骤:
以下是一个简单的示例代码:
import UIKit
class CustomTableViewCell: UITableViewCell {
let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = .black
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
titleLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10),
titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10),
titleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let tableView: UITableView = {
let tableView = UITableView()
tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
cell.titleLabel.text = "Cell \(indexPath.row)"
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
}
在这个示例中,我们创建了一个名为CustomTableViewCell的自定义UITableViewCell类,并在其中定义了一个UILabel元素。然后,在ViewController类中,我们注册了CustomTableViewCell,并设置了其高度为50。在cellForRowAt:方法中,我们创建了CustomTableViewCell实例,并设置了其UI元素的值。最终,我们在UITableView中显示了10个自定义UITableViewCell实例。
领取专属 10元无门槛券
手把手带您无忧上云