我正在构建一个聊天应用程序,其中每个消息都会插入到表格中的一行中。每行包含一个头像和一条消息。我想根据要放置的文本长度设置UITextArea的宽度和高度。
以下是我使用的代码。但在这里,高度和宽度都是固定的(200x50)
PS:我是Swift和iOS的新手,我正在使用Swift 3。我搜索到的所有代码都是objective-c或swift 2
以下是我使用的代码。但在这里,高度和宽度都是固定的(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
}
boundingRect(with:options:attributes:context:)
,这是NSString
的一个方法。您可以使用此方法计算整个字符串的大小,然后相应地设置textView
和单元格高度。 - Eric Qian