Swift - 减少UICollectionViewCell之间的差距

时间:2015-06-03 16:48:16

标签: ios swift autolayout

我的UICollectionViewCell看起来不太好,即使我在UICollectionViewCell检查员中实施了自动布局和一些设置。

我的设置就像这样

enter image description here

我的UICollectionViewCell自动布局

enter image description here

我的ImageView自动布局

enter image description here

我的代码

PopularViewController.swift

import UIKit
import Alamofire

class PopularViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    var users: [JSON] = []
    @IBOutlet var collectionView: UICollectionView!

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //#warning Incomplete method implementation -- Return the number of items in the section
        return users.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("UserCell", forIndexPath: indexPath) as! PopularCollectionViewCell

        cell.user = self.users[indexPath.row]
        return cell
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(.GET, "http://128.199.160.213/datetick/users.json").responseJSON { (request, response, json, error) in

            if json != nil {
                var jsonObj = JSON(json!)
                if let data = jsonObj["users"].arrayValue as [JSON]?{
                    self.users = data
                    self.collectionView.reloadData()
                }
            }

        }
    }
}

PopularCollectionViewCell.swift

class PopularCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var profilePicture:UIImageView!

    var user:JSON?{
        didSet{
            self.setupUser()
        }
    }

    func setupUser(){

        if let urlString = self.user?["profilePhoto"]{
            let url = NSURL(string: urlString.stringValue)
            self.profilePicture.hnk_setImageFromURL(url!)
        }

    }
}

我的输出

enter image description here

1 个答案:

答案 0 :(得分:0)

我知道回复的时间已晚,但对其他人可能有用。

您可以使用UICollectionViewDelegateFlowLayout缩小大小。您已在PopularViewController中继承了此类

使用以下功能

//To Show 3 items per row
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: (collectionView.frame.size.width - 3)/3, height: 110)
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
    return 1
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
    return 1
}