【发布时间】:2018-03-15 04:23:10
【问题描述】:
我里面有一个 tableView 和一个 UITextView。我正在尝试将 JSON 中的数据添加到表视图中,但它不会根据大小收缩/扩展。我尝试了很多论坛和方法。
主要问题是 - 如果它随着高度开始膨胀/收缩,它就会停止收缩/膨胀,反之亦然。机器人高度和宽度不起作用。
这是因为,当我将 UITextView 的尾随和前导约束设置为单元格时,它开始使用高度但停止使用宽度。当我删除前导/尾随约束时,UITextView 的内容会超出屏幕并且不会以多行形式出现,即不会随高度扩展。我已经尝试过 -
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
}
我不希望文本视图可编辑。由于我不熟悉Objective C,请迅速回复。谢谢
编辑:自定义单元格代码
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
}
}
【问题讨论】:
-
在单元格中,您是否将 textView 作为子视图添加到单元格或 contentView ?需要添加到contentView并在contentView上添加约束
-
是的,我已添加到 contentView。约束也被添加到 contentView。
-
您可以发布自定义单元格的代码吗?
-
自定义单元格几乎是样板代码。我可以发布它。检查编辑
-
另外你为什么不使用 numberOfLines = 0 的
UILabel而不是UITextView。
标签: ios swift uitableview uitextview