【发布时间】:2019-09-04 15:31:20
【问题描述】:
我尝试为我的应用程序添加问答部分,并且 tableview 单元格必须根据文本高度扩展,单元格高度必须随此文本而变化。在这一点上,我做了一些事情来解决 numberOfline = 0 和 UITableView.automaticDimension 代码无法解决我的问题的问题。这是我的项目代码:
问题是单元格高度没有更改此代码,只需在问题下方写标签,并在下一个问题下获得更长的答案。意味着单元格高度没有改变。
let soruLabel: UILabel = {
let sorulabel = UILabel()
sorulabel.textColor = .darkGray
sorulabel.numberOfLines = 0
sorulabel.font = UIFont.boldSystemFont(ofSize: 17)
return sorulabel
}()
let cevapLabel: UILabel = {
let cevaplabel = UILabel()
cevaplabel.textColor = .black
cevaplabel.numberOfLines = 0
cevaplabel.font = UIFont(name: "HelveticaNeue", size: 18)
return cevaplabel
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
func set(content: expandingTableCellForsss) {
self.soruLabel.text = content.soru
self.cevapLabel.text = content.expanded ? content.cevap : ""
}
func setup() {
backgroundColor = UIColor.init(red: 245, green: 245, blue: 245, alpha: 1)
addSubview(soruLabel)
addSubview(cevapLabel)
soruLabel.translatesAutoresizingMaskIntoConstraints = false
soruLabel.topAnchor.constraint(equalTo: topAnchor).isActive = true
soruLabel.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
soruLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = false
soruLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
cevapLabel.translatesAutoresizingMaskIntoConstraints = false
cevapLabel.topAnchor.constraint(equalTo: soruLabel.bottomAnchor).isActive = true
cevapLabel.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
cevapLabel.bottomAnchor.constraint(equalTo: soruLabel.bottomAnchor).isActive = false
cevapLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
【问题讨论】:
-
要使用 UITableView.automaticDimension 你还需要设置estimatedHeightForRowAt
-
检查cevapLabel的底部约束,它没有连接到容器视图的底部。以防万一还要检查内容拥抱优先级。
-
cevapLabel底部锚不应该等于bottomAnchor并且激活吗?具体来说:cevapLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true?
-
@DavidSteppenbeckPhD 非常感谢您解决了我的问题。
-
@eksglox 没问题,我将其添加为答案,以便其他用户可以轻松找到它。如果对您有用,请标记为已接受。
标签: swift xcode uitableview dynamic-sizing