在tableview中的UItexView后面附加一个UIimage



我在tableview单元格中附加了一个UItextView。现在我想在它后面插入一个UI图像,就像聊天气泡一样。但每次我滚动表视图时,Uitextview的宽度会变小,高度会变长。文本的大小也从单行调整为多行。此外,当我滚动回以前的单元格(例如第一行)时,也会发生同样的情况。我不明白为什么会发生这种事。

我的代码是:(SampleTableViewCell是我的自定义UItableViewCell类,而lblTitle则是我的UitextView出口。)

func tableView(tableView: UITableView, willDisplayCell cell: SampleTableViewCell, forRowAtIndexPath indexPath: NSIndexPath) 
 {
    cell.lblTitle.removeConstraints(cell.lblTitle.constraints)
    let stringTitle = carName[indexPath.row] as String //carName is an array
    cell.lblTitle.text=stringTitle
    cell.lblTitle.sizeToFit()
    let h = cell.lblTitle.frame.size.height
    let w = cell.lblTitle.frame.size.width
    let constraints = NSLayoutConstraint(item: cell.lblTitle, attribute: .Width, relatedBy: .Equal, toItem: cell.lblTitle, attribute: .Height, multiplier: 0, constant: w)
    cell.lblTitle.addConstraint(constraints)
    let kl = UIImage(imageLiteral: "bubble")
    let imageView  = UIImageView(frame:CGRectMake(0, 0, w, h))
    imageView.image = kl
    imageView.alpha = 0.4
    cell.lblTitle.addSubview(imageView)
    cell.lblTitle.sendSubviewToBack(imageView)
  }  

这是自动布局的问题。

您只是给textView设置了高度和宽度限制。x和y的位置呢?

而且您还没有为您的imageview设置约束!!

如果你对一个对象施加约束,那么你需要给出与之相关的每个对象

因此,设置适当的约束条件,您的问题就会得到解决。

使用故事板,您可以先在tableview单元格中添加imageview,然后在与imageview大小相同的UITextView中添加约束,而不是以编程方式添加气泡imageview和约束。然后,您可以在cellForRowAtIndexPath委托中为lblTitle的文本和气泡图像添加逻辑。请确保将lblTitle的背景设置为ClearColor。

最新更新