ios - Programmatically adding UIImage into collection view cell -
this custom class collection view cell:
import uikit class navbarcell: uicollectionviewcell { var avatarimageview: uiimageview = { var avatarview = uiimageview() avatarview.contentmode = .scaleaspectfit return avatarview }() override init(frame: cgrect) { super.init(frame: frame) avatarimageview = uiimageview() contentview.addsubview(avatarimageview) } required init?(coder adecoder: nscoder) { fatalerror("init(coder:) has not been implemented") } }
then in viewdidload
of controller have
let layout:uicollectionviewflowlayout = uicollectionviewflowlayout.init() navbarcollectionview.setcollectionviewlayout(layout, animated: true) navbarcollectionview.backgroundcolor = uicolor.clear navbarcollectionview.register(navbarcell.self, forcellwithreuseidentifier: "cell") navbarcollectionview.delegate = self navbarcollectionview.datasource = self layout.scrolldirection = .horizontal self.navigationcontroller?.navigationbar.addsubview(navbarcollectionview) navbarcollectionview.reloaddata()
and in cellforitem
have:
let navbarcell = (collectionview.dequeuereusablecell(withreuseidentifier: "cell", for: indexpath)) as! navbarcell var image : uiimage = uiimage(named: "testimage")! navbarcell.avatarimageview.image = image navbarcell.avatarimageview.layer.borderwidth = 1 navbarcell.avatarimageview.layer.bordercolor = uicolor.getrandomcolor().cgcolor navbarcell.avatarimageview.layer.cornerradius = 20 return navbarcell
but image views not showing up. if add navbarcell.backgroundcolor = uicolor.red
cells show up, not images.
anything i'm missing, or not implementing correctly?
uicollectionviewcell
view, can add avatarimageview
directly it:
addsubview(avatarimageview)
you can set constraints, example:
avatarimageview.translatesautoresizingmaskintoconstraints = false avatarimageview.topanchor.constraint(equalto: topanchor).isactive = true avatarimageview.leftanchor.constraint(equalto: leftanchor).isactive = true avatarimageview.rightanchor.constraint(equalto: rightanchor).isactive = true avatarimageview.heightanchor.constraint(equaltoconstant: 300).isactive = true
Comments
Post a Comment