在UITableViewCell中展开UITextView高度(阅读更多效果)

问题描述:

我试图用动画展开UITextView,当用户点击阅读更多按钮时,它会在下面展开。在UITableViewCell中展开UITextView高度(阅读更多效果)

enter image description here

我已经尝试了很多的方法,并提出了几乎工作液:

func readMore() { 
    self.tableView.beginUpdates() 
    cell.descTextViewHeightConstraint.constant = cell.descTextView.expectedHeight() 
    self.tableView.endUpdates() 
} 

的UITextView +身高

extension UITextView { 
    func expectedHeight() -> CGFloat { 
     let textView: UITextView = UITextView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude)) 
     textView.font = self.font 
     textView.text = self.text 
     textView.sizeToFit() 
     return textView.frame.height 
    } 
} 

此解决方案,但是有一个sideeffect - 当动画结束时,隐藏UITableViewCell中的一些元素(标题标签)。

我也试图在动画完成时调用tableView.reloadData(),它可以工作,但有时也有副作用。

+1

几乎每天都会问到这个问题,这就是为什么我创建了这个示例项目https://github.com/bavarskis/ExpandingTableViewCell.git看看它,它非常简单。 –

+0

我在我的代码中发现了一个错误,导致我提到的一个副作用(点击时按钮读取更多并未隐藏)。我在cellForRow函数中以编程方式创建了read more按钮。问题在于,当我不止一次滚动到该单元格时,该按钮每次都会创建,并且只有最后创建的那个被隐藏。 –

为什么不使用numberOfLines属性“玩”?

对于一个项目,我做了类似这样的事情(还有一个UIImage箭头旋转了......)。一切都是一个自定义单元格类中:

func setExpanded(_ isExpanded: Bool) { 
    if isExpanded { 
     lblFullDescription.numberOfLines = 0 
     UIView.animate(withDuration: Constants.NavigationBar.AnimationTime, animations: { [weak self] in 
      self?.imgArrow.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)) 
     }) 

    } else { 
     lblFullDescription.numberOfLines = 2 
     UIView.animate(withDuration: Constants.NavigationBar.AnimationTime, animations: { [weak self] in 
      self?.imgArrow.transform = CGAffineTransform(rotationAngle: CGFloat(0)) 
     }) 
    } 
} 

而且在ViewController中添加此持有的的UITableView:

tableView.rowHeight = UITableViewAutomaticDimension 
tableView.estimatedRowHeight = 42 
+0

我试过这种方法。它的工作,但问题是,它从底部“动画”。当我将行数设置为2时,我可以看到前两行的内容,这很好。但是,当我将行数设置为0时,我只能看到标签中最后两行的内容(不是前两行),而在动画期间,内容与底部相关,所以我将第一行竞争对手最后显示。 –

可以对细胞的回调和更新它的约束

func updateTableViewUIfor(indexPath: IndexPath) { 
    self.tableView.beginUpdates() 
    theCell.updateToExpanded() //get the cell and update it's constraints 
    self.tableView.setNeedsDisplay() 
    self.tableView.endUpdates() 
} 

并且您使用

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
//... return required height 
} 
+0

tableView.setNeedsDisplay没有帮助。动画工作后,只有tableView.reloadData()。 –

我有一些问题与iOS 11和自我大小/可调整大小的单元格。我不知道eactyl对你来说有什么奇怪的行为,但在我的情况下,我确实将tableView estimatedRowHeight设置为一个大于我的最大单元高度的值,并解决了它。

+0

我有不同的错误,我在问题评论中描述了它。但是,感谢您的意见。可能帮助别人。 –