【发布时间】:2016-10-20 01:03:43
【问题描述】:
我正在构建一个聊天应用程序,其中每条消息都插入到表格内的一行中。每行包含一个头像和一条消息。我想根据要放入的文本长度设置 UITextArea 的宽度和高度。
以下是我使用的代码。但是在这里,高度和宽度都是恒定的(200x50)
PS:我是 Swift 和 ios 的新手,我正在使用 Swift 3。我搜索后得到的每个代码都在 Objective-c 或 swift 2 中
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("ChatBox1", owner: self, options: nil)?.first as! ChatBox1
let myTextField: UITextView = UITextView(frame: CGRect(x: 30, y: 20, width: 200.00, height: 50.00));
cell.addSubview(myTextField)
myTextField.isScrollEnabled = false
myTextField.isUserInteractionEnabled = false
myTextField.backgroundColor = UIColor.lightGray
myTextField.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
myTextField.layer.cornerRadius = 5
print(myTextField.intrinsicContentSize)
let image = UIImage(named: "agent")
let imageView = UIImageView(image: image)
imageView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
cell.addSubview(imageView)
return cell
}
【问题讨论】:
-
试试 cell.sizeToFit()
-
看看
boundingRect(with:options:attributes:context:),这是NSString的一个方法。您可以使用此方法计算整个字符串的大小,然后相应地设置textView以及单元格高度 -
尝试 cell.sizeToFit() 并尝试在您的行数内...... tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension。这将解决您的问题....
-
与您的 texfield 无关。请查看我的其他评论。这就是您要寻找的答案......
-
在你的 func tableView(tableView:UITableView!, numberOfRowsInSection section: Int) -> Int { return yourArray.count }
标签: ios swift uilabel uitextview swift3