这是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
}
}
你必须根据需要在sizeForItemAtIndexPath方法来清理格式。
希望这会有所帮助!
想更多地了解这一点,如果标签的顺序并不重要,那么我会写一个排序函数来优化布局(并且可能会做充分的理由)。 – DJohnson