【发布时间】:2019-02-18 18:29:19
【问题描述】:
我有一个包含五个单元格的 UICollectionView。在那里,我有一个 UIImageView、两个 UILabel 和一个 UITextView。我想根据它包含的文本更改 textview 的高度,所以之后我可以根据 UITextView 的高度和它们上方的标签来设置整个单元格的高度。让我演示一下with a screenshot。
所以,如您所知,红色背景显示 UITextView 的高度不正确。我这样设置 UITextView:
let commentTextView: UITextView = {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.text = "This is just some text to act as a description"
textView.textContainerInset = UIEdgeInsets(top: 0, left: -4, bottom: 0, right: 0)
textView.font = UIFont.systemFont(ofSize: 16.0)
textView.textColor = UIColor.darkGray
textView.isEditable = false
textView.isSelectable = false
textView.backgroundColor = UIColor.red
textView.frame.size.width = (UIScreen.main.bounds.width - 16 - 16 - 60 - 8)
let numberOfLines = (textView.contentSize.height / textView.font!.lineHeight)
var textViewHeight = (textView.font?.lineHeight)! * floor(numberOfLines)
textView.frame.size.height = textViewHeight
return textView
}()
我认为这不会造成错误的高度。我认为问题可以在我的约束中找到,它有一个高度约束(如果我删除它, UITextView 就会消失)。如果我更改乘数(当前设置为 0.3),我有不同的高度,但我希望这是动态的。所以在我看来,我需要在乘数内设置一个动态变量,但我不知道如何组合它。有人可以帮忙吗?这是我的限制:
// top constraints
addConstraints([NSLayoutConstraint(item: commentTextView, attribute: .top, relatedBy: .equal, toItem: workoutLabel, attribute: .bottom, multiplier: 1, constant: 2)])
// left constraint
addConstraints([NSLayoutConstraint(item: commentTextView, attribute: .left, relatedBy: .equal, toItem: profilePictureImageView, attribute: .right, multiplier: 1, constant: 16)])
// right constraint
addConstraints([NSLayoutConstraint(item: commentTextView, attribute: .right, relatedBy: .equal, toItem: self.commentTextView.superview, attribute: .right, multiplier: 1, constant: -16)])
// height constraint
addConstraints([NSLayoutConstraint(item: commentTextView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0.3, constant: 1)])
干杯!
【问题讨论】:
标签: ios swift xcode constraints uitextview