介绍
背景:
我正在创建一个应用程序,但遇到了一个问题,我无法解决。
我有一个tableView,其中包含许多UI元素的单元格。所有约束都使用EasyPeasy库完成,该库基本上只设置自动布局约束(我也尝试手动设置它们)。所讨论的UITextView通过各种数字被约束到左侧、右侧、顶部和底部,但我没有对其高度或宽度进行约束。
在cellForRowAt indexPath中:我为每个单元格的textView设置了self委托,使用了在单元格自定义类中声明的delegate属性。我还使用其单元格indexPath.row来标记每个textView(在textViewDidChange方法中给出
textView.tag
整数)。
问题/认识:
- 浏览了很多SO后,我找到了一些类似这样的问题,但我无法使它们对我起作用,我已经实现了它们的一部分,感觉对我的情况很有逻辑。我认为,区别于那些问题的问题在于,为了使我的cell设计工作,cell必须具有
itemHeight
或更高的高度。 - 我注意到,当我输入文本时,文本视图本身会增加高度(甚至超过了单元格的边框,但由于达到该点而不可见),但是单元格本身不会调整大小。
- 我尝试了一个只包含textView的单元格,因此问题必须在textViewDidchange或heightForRowAt indexPath方法中。
问题:
我在这里做错了什么?为什么单元格的高度不随我在textView中输入而动态更改?
代码:
func textViewDidChange(_ textView: UITextView) {
var newframe = textView.frame
newframe.size.height = textView.contentSize.height - textView.frame.size.height + itemHeight[textView.tag]
textView.frame = newframe
let ndxPath = IndexPath(row: textView.tag, section: 0)
let cell = tableView.cellForRow(at: ndxPath) as! EventsCell
cell.frame = CGRect(x: cell.frame.origin.x, y: cell.frame.origin.y, width: cell.frame.width, height: textView.frame.height)
tableView.beginUpdates()
tableView.setNeedsLayout() //have tried without this line
tableView.layoutIfNeeded() //have tried without this line
tableView.endUpdates()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if UITableViewAutomaticDimension > itemHeight[indexPath.row] {
return UITableViewAutomaticDimension
} else {
return itemHeight[indexPath.row]
}
}
TextView约束条件:
let containerView : UIView = {
let cv = UIView(frame: .zero)
cv.backgroundColor = .white
cv.translatesAutoresizingMaskIntoConstraints = false
cv.layer.cornerRadius = 7
return cv
}()
let eventText : GrowingTextView = { // GrowingTextView is a extension to a regular UITextView
let tv = GrowingTextView()
tv.allowsEditingTextAttributes = true
tv.isScrollEnabled = false
var delegate: UITextViewDelegate?
tv.textContainerInset = UIEdgeInsetsMake(1, 1, 0, 1)
tv.autoresizingMask = .flexibleHeight
tv.translatesAutoresizingMaskIntoConstraints = false
return tv
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
containerView.addSubview(eventText)
contentView.addSubview(containerView)
containerView .easy.layout([Height(CGFloat(95 * itemCount)), Left(8), Right(8)])
eventText .easy.layout([Left(77), Right(5), Top(90), Bottom(4)])
}
感谢阅读我的帖子。
UIView.addSubview(textView)
然后contentView.addSubview(textView)
。我已经在编辑中添加了textView的约束代码。 - theoadahl