根据动态文本设置UITextView的宽度和高度

Gijo Varghese

我正在构建一个聊天应用程序,其中每个消息都插入到表格内的一行中。每行包含一个头像和一条消息。我想根据要放入其中的文本的长度设置UITextArea的宽度和高度。

以下是我使用的代码。但是在这里,高度和宽度都是恒定的(200x50)

PS:我是Swift和ios的新手,正在使用Swift3。搜索后得到的每个代码都在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
    }

在此处输入图片说明

试试这个代码:

答1:

   func tableView(tableView:UITableView!, numberOfRowsInSection section: Int) -> Int { 

        yourTableViewName.estimatedRowHeight = 44.0 // Standard tableViewCell size
        yourTableViewName.rowHeight = UITableViewAutomaticDimension

   return yourArrayName.count } 


   And also put this code inside your Cell for incase...
   yourCell.sizeToFit() 

答案2:

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章