我里面有一个tableView和一个UITextView . 我正在尝试将数据从JSON添加到表视图,但它不会根据大小缩小/扩展 . 我尝试了很多论坛和方法 .
主要问题是 - 如果它开始随高度膨胀/收缩,它会停止收缩/扩展,反之亦然 . 机器人的高度和宽度不起作用 .
This is because, when I set the trailing and leading constraints of the UITextView to the cell, it starts working with height but stops working with width. When I remove the leading/trailing constraints, the content of the UITextView goes beyond the screen and does not come as multiline i.e. does not expand with height. 我试过 -
How do I size a UITextView to its content?
How to resize table cell based on textview?
还有很多很喜欢这些 .
我的一点代码 -
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Message") as! TextViewCell
cell.customTextView.textColor = UIColor.white
// Give a source to table view cell's label
cell.customTextView.text = requestResponseArr[indexPath.row]
cell.translatesAutoresizingMaskIntoConstraints = true
cell.sizeToFit()
if (indexPath.row % 2 == 0) {
cell.customTextView.backgroundColor = ConstantsChatBot.Colors.iMessageGreen
cell.customTextView.textAlignment = .right
} else {
cell.customTextView.backgroundColor = ConstantsChatBot.Colors.ButtonBlueColor
cell.customTextView.textAlignment = .left
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
并在viewDidLoad()中 -
override func viewDidLoad() {
// RandomEstimatedRowHeight
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300
}
我不希望textview可以编辑 . 由于我不熟悉Objective C,请用swift回复 . 谢谢
编辑:自定义单元格代码
class TextViewCell: UITableViewCell {
@IBOutlet weak var customTextView: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
customTextView.isScrollEnabled = false
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
4 回答
我在
UITableViewCell
内尝试了UITextView
.Constraints
UITextView
,顶部,底部和右侧为2,2和5,宽度为50.Font Size
为13,Alignment
为中心 . 为Width constraints
提供Outlet connection
为txtVwWidthConst
UIViewController
UITableViewCell
Output
Note
仅
UITextView
,我们必须计算字符串大小 . 但是,在UILabel
中,这个概念非常简单 . 如果您有任何疑问,请告诉我 .您需要为此禁用
UItextView
滚动 .并在单元格中添加textview的顶部,底部,右侧和左侧约束 . 并添加高度约束> = 10
您需要为textview设置所有四个约束,即前导,尾随,顶部和底部让我们将所有约束设置为8 .
它看起来如下所示:
在GitHub上查看演示here
在
cellForRowAt
内禁用UITextViewisScrollEnabled
是false
Demo Example