布局 – CollectionView动态单元格高度swift

我试图创建一个集合视图,其中单元格显示具有可变长度的字符串.

Im使用此功能设置单元格布局:

func collectionView(collectionView : UICollectionView,layout collectionViewLayout:UICollectionViewLayout,sizeforItemAtIndexPath indexPath:NSIndexPath) -> CGSize
    {
        var cellSize:CGSize = CGSizeMake(self.whyCollectionView.frame.width,86)
        return cellSize
    }

我想做的是根据我的cell.labelString.utf16Count长度操纵cellSize.height.
基本逻辑就是这样

if((cell.labelString.text) > 70){
   cellSize.height = x
}
else{
   cellSize.height = y
}

但是,我无法检索我的单元格标签长度,总是返回nil. (我觉得没有加载…

为了更好的理解,这里是完整的代码

// WhyCell section
    var whyData:NSMutableArray! = NSMutableArray()
    var textLength:Int!
    @IBOutlet weak var whyCollectionView: UICollectionView!

//Loading data
    @IBAction func loadData() {
        whyData.removeAllObjects()

        var findWhyData:PFQuery = PFQuery(className: "PlacesWhy")
        findWhyData.whereKey("placeName",equalTo: placeName)

        findWhyData.findobjectsInBackgroundWithBlock({
            (objects:[AnyObject]!,error:NSError!)->Void in

            if (error == nil) {
                for object in objects {
                    self.whyData.addobject(object)
                }

                let array:NSArray = self.whyData.reverSEObjectEnumerator().allObjects
                self.whyData = array.mutablecopy() as NSMutableArray

                self.whyCollectionView.reloadData()
                println("loadData completed. datacount is \(self.whyData.count)")
            }
        })
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.loadData()


    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
        return whyData.count
    }

    func collectionView(collectionView: UICollectionView,cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell:whyCollectionViewCell = whyCollectionView.dequeueReusableCellWithReuseIdentifier("whyCell",forIndexPath: indexPath) as whyCollectionViewCell

        // Loading content from NSMutableArray to cell
        let therew:PFObject = self.whyData.objectAtIndex(indexPath.row) as PFObject
        cell.userWhy.text = therew.objectForKey("why") as String!
        textLength = (therew.objectForKey("why") as String!).utf16Count
        self.whyCollectionView.layoutSubviews()

        // displaying user information
        var whatUser:PFQuery = PFUser.query()
        whatUser.whereKey("objectId",equalTo: therew.objectForKey("reasonGivenBy").objectId)

        whatUser.findobjectsInBackgroundWithBlock({
            (objects: [AnyObject]!,error: NSError!)->Void in

            if !(error != nil) {
                if let user:PFUser = (objects as NSArray).lastObject as? PFUser {
                    cell.userName.text = user.username
                    // Todo display avatar
                }

            }
        })

        return cell
    }

    func collectionView(collectionView : UICollectionView,86)
        return cellSize
    }
您可以在cellForItemAtIndexPath函数中动态设置单元格的框架,因此如果忽略sizeforItemAtIndexPath函数,您可以根据标签自定义高度.通过自定义大小,您可能需要查看集合视图布局流程,但希望这可以指向正确的方向.它可能看起来像这样:
class CollectionViewController: UICollectionViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

    var array = ["a","as","asd","asdf","asdfg","asdfgh","asdfghjk","asdfghjklas","asdfghjkl","asdghjklkjhgfdsa"]
    var heights = [10.0,20.0,30.0,40.0,50.0,60.0,70.0,80.0,90.0,100.0,110.0] as [CGFloat]

    override func viewDidLoad() {
        super.viewDidLoad()
    }


    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
        return array.count
    }

    override func collectionView(collectionView: UICollectionView,cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellID",forIndexPath: indexPath) as Cell
            cell.textLabel.text = array[indexPath.row]
            cell.textLabel.sizetoFit()

            // Customize cell height
            cell.frame = CGRectMake(cell.frame.origin.x,cell.frame.origin.y,cell.frame.size.width,heights[indexPath.row])
            return cell
    }

    func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeforItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSizeMake(64,64)
    }
}

这给了动态高度

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...