【发布时间】:2017-11-23 13:26:11
【问题描述】:
我有一个UICollectionView,其中包含UICollectionViewCells,其中包含UIButtons 用于内容。
但是每个单元格之间的间距不正确不正确。集合视图中的单元格没有特定的大小,因为它应该是一个长度明显不同的标签列表。
这是它的样子:
每个单元格之间的水平间距完全不正确,因为它们因行而异。
单元格的代码:
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var wordsCollection: UICollectionView!
var items = ["test", "this", "word view", "like", "collection", "testing", "give", "this", "testing", "test", "test", "this", "word view", "like", "collection", "testing", "give", "this", "testing", "test", "test", "this", "word view", "like", "collection"]
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "wordCell", for: indexPath as IndexPath) as! WordCell
cell.wordButton.setTitle(items[indexPath.row], for: UIControlState.normal)
cell.wordButton.backgroundColor = UIColor.gray
if(indexPath.row % 3 == 0){
cell.wordButton.backgroundColor = UIColor.gray
}
cell.wordButton.clipsToBounds = true
cell.wordButton.layer.cornerRadius = 2
cell.wordButton.sizeToFit()
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
if let flowLayout = wordsCollection.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSize(width:1, height:1) }
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
语言是 Swift 4,我的目标是 iOS 10.3。
【问题讨论】:
-
你还没有实现 UICollectionview 的 Flow Layout 委托,然后实现方法 interItemSpacing 和 minimumLineSpacing
标签: ios uicollectionview uicollectionviewcell