要解决不同设备上UITableViewCell的textLabel内边距发生变化的问题,可以使用以下方法:
class CustomTableViewCell: UITableViewCell {
let customLabel = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(customLabel)
customLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
customLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
customLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
customLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
customLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// 在tableView(_:cellForRowAt:)方法中使用如下代码
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Example Text"
// 设置内边距
cell.layoutMargins = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16)
cell.separatorInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
return cell
}
这样,无论在哪种设备上,都可以保持UITableViewCell的textLabel内边距一致。