swift - Swift - 具有动态高度的 UICollectionViewCells
问题描述
我正在开发一个聊天应用程序,但我不知道如何使UICollectionViewCell
s 的高度动态化,具体取决于UITextView
s 的文本有多大。
这是我一直在测试的;
class ViewController: UIViewController {
@IBOutlet var cv: UICollectionView!
let arr = ["hi hello", "func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell", "func collectionView", "// Do any additional setup after loading the view.", "extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let flowLayout = cv.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
flowLayout.itemSize = UICollectionViewFlowLayout.automaticSize
}
// setup cv constraints here
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mm", for: indexPath) as! MessageCollectionViewCell
cell.setup(text: arr[indexPath.row])
return cell
}
}
这是我手机的密码;
class MessageCollectionViewCell: UICollectionViewCell {
@IBOutlet var tv: UITextView!
func setup(text: String) {
tv.text = text
tv.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tv.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 0),
tv.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 8),
tv.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -8),
tv.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: 0)
])
}
}
知道我错过了什么吗?
解决方案
我终于修好了!我应该做的就是为单元格本身添加一个宽度约束,这样它就不会在水平方向上变得更大!
NSLayoutConstraint.activate([
self.contentView.widthAnchor.constraint(equalToConstant: maxDeviceWidth)
])
推荐阅读
- python - 即使连接关闭,Pandas read_sql_query 仍在后台运行?
- laravel - 间接修改重载属性Model没有效果
- postgresql - 即使增加了 work_mem 大小,性能也没有提高
- c++ - C++ ternary assignment of lambda
- ios - 如何在共享扩展的发布操作上显示进度条或加载器
- ruby-on-rails - 找不到资源时如何返回 404,而不是 HTML
- python - 将用户输入与字典和列表进行比较
- html - 如何使用纯 CSS 创建动画表单占位符
- amazon-web-services - 如何在放大中设置 lambda 函数的触发器?
- javascript - 对 jquery 中的 css 函数 @media screen 和 (max-width: 768px) 有任何倡议吗?