【问题标题】:Collection View Grid iOS Swift 2集合视图网格 iOS Swift 2
【发布时间】:2016-02-24 02:29:08
【问题描述】:

所以我有一个工作集合视图,每列有 2 列和 3 个项目。在我使用 iPhone 5s 模拟器之前,网格视图效果很好,然后我的网格视图变成了一列而不是 2 列。我已经阅读了一堆关于自定义布局的帖子,但它们似乎都不起作用。任何帮助表示赞赏。这是我的代码:

 override func viewDidLoad() {
    super.viewDidLoad()
    let screenWidth = UIScreen.mainScreen().bounds.size.width
    let screenHeight = UIScreen.mainScreen().bounds.size.height


    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
    layout.itemSize = CGSize(width: (screenWidth - 32)/2, height: 175)

    var collview = UICollectionView(frame: CGRectMake(0, 0, screenWidth, screenHeight), collectionViewLayout: layout)


    [collview.reloadData];


}  
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

   let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell

    let myImage = UIImage(named: pictureArray[indexPath.row])

    cell.textView.text = textArray[indexPath.row]

    cell.imageView.image = myImage


    return cell
}

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

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
    return CGSize(width: 175, height: 175)
}

【问题讨论】:

    标签: ios swift grid uicollectionview uicollectionviewlayout


    【解决方案1】:

    因为你为每个项目设置的大小是CGSize(width: 175, height: 175),所以当你换其他手机时,它就不能正常工作了。

    就这样改:(把UICollectionViewDelegate改成UICollectionViewDelegateFlowLayout

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {
        return CGSize(width: screenWidth / 3, height: screenWidth / 3)
    }
    

    【讨论】:

    • 我收到一条错误消息,提示“UIView 的值类型没有成员大小”
    • 我刚刚更新了答案,请再次查看。您可以使用 collectionView.size.frame.width / 3
    • 奇怪,现在说 UICollectionView 的值没有成员大小。我的代码做错了吗?
    • 所以,你可以使用 screenWidth / 3
    • 太棒了,这行得通,但现在我的单元格大小比它们应该的要小。我希望单元格的高度和宽度为 175,我认为它们默认为 50。
    猜你喜欢
    • 2015-05-23
    • 2020-04-16
    • 1970-01-01
    • 2018-03-24
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    相关资源
    最近更新 更多