ios - UICollectionView 中单元格之间的零水平间距不起作用

标签 ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

我是 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/

相关文章:

ios - 当点击 iOS Swift 中的“下一步”按钮时,如何在 TableView 中加载数据数组?

ios - 是否可以为返回的指针分配一个新值?

testing - 是否可以使用 XCode 的 SenTestingKit 对静态库项目进行单元测试?

iphone - Push ViewController 带模态动画(水平翻转)

arrays - 将原始数组与辅助数组进行比较,如果与原始数组匹配则更改值

swift - 如何在适用于 XCTest 的 FileManager 中生成可写路径

ios - swift : Swipe Both UICollectionView and UIPageViewController

ios - 用户默认值 Swift

ios - 使用自定义 UICollectionViewLayout 时出现“-layoutAttributesForItemAtIndexPath 没有 UICollectionViewLayoutAttributes 实例”错误

swift - 为什么我的渐变层覆盖了我的 collectionView 单元格?