progammingBeignner progammingBeignner - 2 months ago 33
iOS Question

Program UICollectionViewCell Programmatically

I am trying to create a cell programmatically without using the story board, but I stumble upon some problems. The cell code is as following.

import UIKit

class ProductCategoryCollectionViewCell: UICollectionViewCell {


required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupCell()
}


var productCategoryImageView :UIImageView!

func setupCell(){
//seting up the imageView as subView
productCategoryImageView = UIImageView()
productCategoryImageView.translatesAutoresizingMaskIntoConstraints = false
let subViewDictionary = ["productCategoryImageViewKey" : productCategoryImageView]


let productCategoryImageViewWidth = contentView.bounds.size.width
let productCategoryImageViewHeight = contentView.bounds.size.height
let productCategoryImageViewHorizontalConstrain = NSLayoutConstraint.constraintsWithVisualFormat("H:[productCategoryImageViewKey(\(productCategoryImageViewWidth))]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: subViewDictionary)
let productCategoryImageViewVerticalConstrain = NSLayoutConstraint.constraintsWithVisualFormat("V:[productCategoryImageViewKey(\(productCategoryImageViewHeight))]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: subViewDictionary)

productCategoryImageView.addConstraints(productCategoryImageViewHorizontalConstrain)


productCategoryImageView.addConstraints(productCategoryImageViewVerticalConstrain)



contentView.addSubview(productCategoryImageView)
contentView.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.4)
}


}

I am trying to create a subImageView which will be size of the cell, however, it doesn't scale to to the size of the cell.

Answer Source

The size of the cell is not known when the init method is called. So setting the width and height to contentView.bounds.size.width and contentView.bounds.size.height won't work.

Instead of adding constraints for horizontal and vertical sizes you can add left, right, top and bottom constraints, like this:

let productCategoryImageViewHorizontalConstrain = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[productCategoryImageViewKey]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: subViewDictionary)
let productCategoryImageViewVerticalConstrain = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[productCategoryImageViewKey]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: subViewDictionary)

And you should also call contentView.addSubview(productCategoryImageView) before adding the constraints.