在不使用常量的情况下获得分组的UITableViewCell内容区域宽度,可以通过以下方法实现:
在UITableView的代理方法中,可以通过获取当前屏幕的宽度来计算UITableViewCell的内容区域宽度。具体实现如下:
func tableView(_ tableView: UITableView, widthForHeaderInSection section: Int) -> CGFloat {
let screenWidth = UIScreen.main.bounds.width
return screenWidth
}
可以使用Auto Layout来自动计算UITableViewCell的内容区域宽度。具体实现如下:
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Cell Content"
cell.textLabel?.numberOfLines = 0
cell.textLabel?.translatesAutoresizingMaskIntoConstraints = false
cell.textLabel?.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 15).isActive = true
cell.textLabel?.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: -15).isActive = true
cell.textLabel?.topAnchor.constraint(equalTo: cell.topAnchor, constant: 0).isActive = true
cell.textLabel?.bottomAnchor.constraint(equalTo: cell.bottomAnchor, constant: 0).isActive = true
return cell
}
通过以上方法,可以在不使用常量的情况下获得分组的UITableViewCell内容区域宽度。
领取专属 10元无门槛券
手把手带您无忧上云