【发布时间】:2021-02-09 09:50:20
【问题描述】:
每个tableviewcell中需要显示一个内容列表,所以这里我在Tableview cell里面使用了tableview。但问题是主 tableview 单元格高度不会根据内容而变化。我不想修复 UITableViewCell 的高度,我希望它根据内容动态调整。
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! SubCell
if indexPath.row%2==0{
cell.backgroundColor = .orange
}else{
cell.backgroundColor = .green
}
return cell
}
class SubCell: UITableViewCell, UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2") as! SubCell2
cell.titleLabel.text = "asdf asdf asdf asdf asdf adfs asdf asdf asdf asdf asdf asdf asd fasd fasd fasd fasd fasd fasd f asdf asdf asdf asdf asd fasd fasd fasd fasd fasd fasdf asdf asd fasd 1234"
return cell
}
@IBOutlet weak var tablView2: UITableView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
class SubCell2: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
预期输出:
实际输出:
约束:
【问题讨论】:
-
如何在单元格中设置约束?这就是“魔法”发生的地方。
-
我添加了另一个截图,请检查。 @Larme
-
您是否检查过:stackoverflow.com/questions/18746929/…?另外,你在 UITableViewCell 中有一个 UITableView 吗?
-
我做了,但没用@Larme ...,
-
@Codecracker - 在 tableView 单元格中“嵌套”tableViews 本质上是有问题的,并且很少给你想要的结果。您是否有不想使用多个 tableView 部分的原因?
标签: ios swift uitableview