gpt4 book ai didi

swift - Collection View 单元格自动布局每个单元格的不同高度

转载 作者:行者123 更新时间:2023-11-30 13:15:39 24 4
gpt4 key购买 nike

问题是我每个单元格都有不同的 UILabel 内容,我希望单元格的宽度固定,高度灵活,具体取决于 UILabel hight 的内容,我尝试了针对此问题的不同解决方案并观看了几个教程,但是不幸的是它不适合我。

**我有一个 View Controller 和两个 Collection View 我只需要其中一个即可拥有灵活的高度 **

extension TextViewController : UICollectionViewDelegateFlowLayout {

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

if collectionView == PagesCollectionView
{
return CGSizeMake(44.0, 44.0)
}
else {

width = UIScreen.mainScreen().bounds.width - CGFloat( 14 )

return CGSizeMake( width , hight )
}


}

编辑1:

是否有一种简单的方法可以像在表格 View 中一样做到这一点?

示例:-

override func viewDidLoad() {

super.viewDidLoad()

self.tableView.estimatedRowHeight = 80
self.tableView.rowHeight = UITableViewAutomaticDimension }

最佳答案

我假设您将在单元格内显示文本

extension TextViewController : UICollectionViewDelegateFlowLayout {

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

if collectionView == PagesCollectionView
{
return CGSizeMake(44.0, 44.0)
}
else {

let width = UIScreen.mainScreen().bounds.width - CGFloat( 14 )
let text = YourDataSource[indexPath.item].text
let size = CGSizeMake(width, 800) // just any arbitrary height to make it compile
let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)
let estimatedFrame = NSString(string: text).boundingRectWithSize(size, options: options, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(16)], context: nil)
return CGSizeMake(width , estimatedFrame.height)
}


}

关于swift - Collection View 单元格自动布局每个单元格的不同高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38258904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com