我是 iOS 开发新手,似乎无法弄清楚为什么我的 Collection View 会间隔开。看起来好像 CSS 中的“margin-right”已应用于每个单元格。我已将单元格和行的“最小间距”设置为零,但仍然发生以下情况...
Screen shot of issue that is occurring
我特意将 Collection View 的背景颜色设置为蓝色,单元格的背景颜色设置为红色,标签的边框颜色设置为黑色,以尝试看看是什么。目标是根本看不到任何“蓝色”( Collection View 背景)。配置 Collection View 后,我调整单元格的宽度以适合标签的固有宽度,但似乎其他单元格的 x 轴位置保持不变...我需要所有单元格聚集在一起。任何帮助将不胜感激!
当前 CollectionViewController 代码...
import Foundation
import UIKit
class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var menu = [
("NEWS"),
("NEIGHBORHOODS"),
("CULTURE"),
("DEVELOPMENT"),
("TRANSPORTATION"),
("CITIES")
]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Testing"
self.navigationController?.navigationBarHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return menu.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("UnderMenuCell", forIndexPath: indexPath) as! UnderMenuCollectionViewCell
cell.underMenuLabel.text = menu[indexPath.row]
let label_width = cell.underMenuLabel.intrinsicContentSize().width + 23
cell.underMenuLabel.layer.zPosition = 1000000
cell.underMenuLabel.layer.borderWidth = 2
cell.underMenuLabel.layer.borderColor = UIColor.blackColor().CGColor
cell.frame.size.width = label_width
return cell
}
}
最佳答案
您可能需要为单元格设置布局属性以指定其宽度:
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attributes.frame = yourFrameHere
attributes.size = yourSizeHere
return attributes
}
您是否还尝试过在 cell.frame.size.width = label_width
处设置断点来查看实际设置的宽度?
关于ios - UICollectionView 中单元格之间的零水平间距不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37062320/