ios - 使 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)])
干杯伙计们!
解决方案
你可以考虑另一种方式dynamic height
。UITextView
它是关于内在内容大小的。您可以使用该技术实现动态高度。
推荐阅读
- python - 我可以使用 python 客户端库将通知从 RaspBerry Pi 发送到 python kivy 应用程序吗?
- javascript - 基本 JS:在光标位置添加字符,同时保持光标位置
- lua - 表排序索引名称 LUA
- java - 如何在 GUI 类中实现 Action Listener?
- android - 为什么作者在 Room 数据库的某个字段中添加@field:SerializedName 注解?
- c - 用C打印素数和的程序
- database - 我们是否必须将密码存储在与 Active Directory 链接的系统中?
- javascript - 它是在循环中调用apis并使用异步等待的写方法吗
- python - 在特定行和列 pandas 的文本开头分配新字符串
- scikit-learn - 如何用 epochs 训练 sklearn svm 模型(sklearn.svm.SVC)?