gpt4 book ai didi

ios - 如何自动计算tableview单元格高度和标签高度

转载 作者:行者123 更新时间:2023-11-29 11:46:23 25 4
gpt4 key购买 nike

对不起,我是swift的初学者。我想获得聊天气泡 View ,但我无法使它整洁。
如何让tableviewcell自动更新高度
非常感谢!

view like this

last two line is emoji

Viewcontroller.swift

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let content = contents[indexPath.row] as Message
let contentWidth:CGFloat = UIScreen.main.bounds.width*0.590
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: contentWidth, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.font = fontTalkContent
label.text = content.content
label.sizeToFit()
var uiHeight:CGFloat = (label.frame.height <= defaultChatroomIconHeight) ? defaultContentHeight : label.frame.height

}

class ChatContentTableViewCell: UITableViewCell {
var labelContent:UILabel = { ()->UILabel in
let ui:UILabel = ChatContent()
ui.font = defaultTextFont
ui.numberOfLines = 0
ui.lineBreakMode = NSLineBreakMode.byWordWrapping
ui.layer.cornerRadius = dafaultLabelContentRadius
ui.layer.masksToBounds = true
ui.isHidden = false
return ui
}()

override func layoutSubviews()
{
super.layoutSubviews()
bulidLoad()

}
func bulidload() {

labelContent.frame = CGRect(x: 0, y: 0, width: contentWidth, height: CGFloat.greatestFiniteMagnitude)

labelContent.sizeToFit()

addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[labelContent]-padding-[icon]-padding-|", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[labelDatetime]-padding-[icon]-padding-|", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-topPadding-[labelContent]-contentAndDatePadding-[labelDatetime]-dateAndBottomPaddding-|", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-topPadding-[icon]", options: [], metrics: metrics, views: views))
}
}

class ChatContent:UILabel {
override init(frame: CGRect) {
super.init(frame:frame)
translatesAutoresizingMaskIntoConstraints = false
numberOfLines = 0
isUserInteractionEnabled = true
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

override func drawText(in rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: defaultContentPadding, left: defaultPadding, bottom: defaultContentPadding, right: defaultPadding)

super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}

最佳答案

使用 UITableViewAutomaticDimension

 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}

关于ios - 如何自动计算tableview单元格高度和标签高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43628281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com