UITextView在Cell Swift中
我一直在搞这些限制几个小时,并不能解决这个问题。 我需要用我的文本视图有dynamic细胞高度。
正如你可以看到它的重叠我的时间戳。 截至目前,我对时间戳没有(没有)限制。 我已经尝试了所有可能的组合来完成这项工作,我不能得到它。
也正在使用
override func viewDidLoad() { super.viewDidLoad() //TableView Cell word wrap (Dynamic Text) self.tableView.dataSource = self self.tableView.delegate = self self.tableView.estimatedRowHeight = 78 self.tableView.rowHeight = UITableViewAutomaticDimension
对于Swift 3.1,4.0
这将通过设置约束和UITableViewAutomaticDimensions
来实现。
步骤1:
第2步:
第3步:
步骤4:
移除UITextView
滚动
第5步:
添加下面的代码,
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension }
注意:
如果你有UILabel
那么从上面的解决schemelabel.numberOfLines = 0
UITextView
replace为UILabel
,并将label.numberOfLines = 0
。
输出:
如果您的单元格高度依赖于文本大小,请按照下列步骤操作:在ViewController.swift中添加该方法
func calculateHeight(inString:String) -> CGFloat { let messageString = inString let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)] let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes) let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil) let requredSize:CGRect = rect return requredSize.height }
设置文本标签的宽度然后调用这个函数:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { heightOfRow = self.calculateHeight(inString: conversations[indexPath.row].description) return (heightOfRow + 60.0) }
对于基本单元格:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension }
此function对于自定义单元格不起作用。
如果您的单元格高度取决于图像高度,则返回图像高度+ someFloatValueAccordingToYourChoice。
希望它能工作。
时间戳和消息之间的用户垂直间距,并将常数设置为> = 2