首页 > 解决方案 > 使 UITextView 高度动态,约束乘数问题

问题描述

我有一个 UICollectionView 包含五个单元格。在那里,我有一个 UIImageView、两个 UILabel 和一个 UITextView。我想根据它包含的文本更改 textview 的高度,所以之后我可以根据 UITextView 的高度和它们上面的标签来设置整个单元格的高度。让我用截图来演示。

所以,如您所知,红色背景显示 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)])

干杯伙计们!

标签: iosswiftxcodeconstraintsuitextview

解决方案


你可以考虑另一种方式dynamic heightUITextView它是关于内在内容大小的。您可以使用该技术实现动态高度。


推荐阅读