ios - Program UICollectionViewCell Programmatically -
i trying create cell programmatically without using story board, stumble upon problems. cell code following.
import uikit class productcategorycollectionviewcell: uicollectionviewcell { required init?(coder adecoder: nscoder) { super.init(coder: adecoder) self.setupcell() } var productcategoryimageview :uiimageview! func setupcell(){ //seting imageview 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 trying create subimageview size of cell, however, doesn't scale to size of cell.
the size of cell not known when init method called. setting width , height contentview.bounds.size.width
, contentview.bounds.size.height
won't work.
instead of adding constraints horizontal , vertical sizes can add left, right, top , bottom constraints, 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 should call contentview.addsubview(productcategoryimageview)
before adding constraints.
Comments
Post a Comment