简体   繁体   中英

Collection view auto layout

I'm making a project to show several images on a iPad, my problem is that I can't make the UICollectionView adjust to the size of the screen, and also when It rotates to landscape the auto layout does not work, I'm really lost with this, any help is very welcome.

Here is a simple example I made on Git: Git project link

Here is some code:

class ViewController: UIViewController {

    @IBOutlet weak var mainMenuCollectionView: UICollectionView!
    var images = ["220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg","220.jpg"]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

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

    func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!
    {
        var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as HomeCollectionViewCell
        cell.imageView.image = UIImage(named:images[indexPath.row])
        cell.textLabel.text = "Woof Woof"
        return cell
    }
}

Thanks in advance.

In you sample project you didn't set up any auto layout constraints. For example the collection view should have 4 constraints: one for each direction: 限制

If you set all the 4 constraints to 0 it will always have the same size as it's container.

For more information you should read the apple developers guide: https://developer.apple.com/library/IOs/documentation/UserExperience/Conceptual/AutolayoutPG/Introduction/Introduction.html

Or start with some tutorials: http://www.raywenderlich.com/50317/beginning-auto-layout-tutorial-in-ios-7-part-1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM