2016-06-01 21 views
0

我不得不建立一個自定義的UITableViewCell,但我不確定如何處理這些內容。指定的設計是這樣的:UITollectionView in UITableViewCell?

我已經整理出來的標籤,邊界和一切,但考慮到事實的內容是動態的,我不知道用什麼來組織它內。

我已閱讀關於FlowLayout,但我不知道如何使用它,也關於UICollectionView,但集合視圖可以提供的所有內容是單元格內的水平滾動,一個功能不符合我的需求。

你能給我一些關於如何實現這一目標的建議嗎?

回答

2

這是UICollectionView的一個非常基本的實現,它使用動態單元大小調整。

class CollectionViewController: UICollectionViewController { 

    @IBOutlet var myCollectionView: UICollectionView! 

    let tags = [ 
    "Web Design", 
    "ADWE", 
    "Busisness functions", 
    "Comics", 
    "Web", 
    "News in the Middle East", 
    "Albanian", 
    "Possession of machetes", 
    "Nuclear physics", 
    "Cookery", 
    "Cross stitiching" 
    ] 

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

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

    } 

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("dynamicCell", forIndexPath: indexPath) 
    cell.layer.borderColor = UIColor.grayColor().CGColor 
    cell.layer.borderWidth = 1.0 
    cell.layer.cornerRadius = cell.frame.height/2.0 
    let tagLabel = cell.viewWithTag(100) as? UILabel 
    tagLabel?.text = tags[indexPath.row] 
    return cell 
    } 

} 

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

    let tagLabel = UILabel() 
    tagLabel.text = tags[indexPath.row] 
    let size = tagLabel.intrinsicContentSize() 
    let cellSize = CGSizeMake(size.width + 40, size.height + 20) //added 40 to width to add space around label. 

    return cellSize 

    } 
} 

enter image description here

你必須根據需要在sizeForItemAtIndexPath方法來清理格式。

希望這會有所幫助!

+0

想更多地瞭解這一點,如果標籤的順序並不重要,那麼我會寫一個排序函數來優化佈局(並且可能會做充分的理由)。 – DJohnson