ios - CollectionView dataSource not working when using UICollectionViewController, but works when using UIViewController with a CollectionView -
i subclassing uicollectionview
, , taking care of datasource
. assign datasource
self
during init
phase of collectionview.
import foundation import uikit class collectionviewsubclass: uicollectionview, uicollectionviewdatasource { public override init(frame: cgrect, collectionviewlayout layout: uicollectionviewlayout) { super.init(frame: frame, collectionviewlayout: layout) datasource = self } public required init?(coder adecoder: nscoder) { super.init(coder: adecoder) datasource = self } public func collectionview(_ collectionview: uicollectionview, numberofitemsinsection section: int) -> int { // called first case, not second return 1 } public func collectionview(_ collectionview: uicollectionview, cellforitemat indexpath: indexpath) -> uicollectionviewcell { // called first case, not second return uicollectionviewcell() } }
- case 1: when use
collectionviewsubclass
insideuiviewcontroller
, works , bothdatasource
methods (numberofitemsinsection
,cellforitemat
called correctly. - case 2: when use
collectionviewsubclass
insideuicollectionviewcontroller
, reasondatasource
methods not called, although when debugged, checkedinit(coder:)
indeed called ,datasource = self
got executed. seems somehow, datasource gotnil
again @ later stage, ,datasource
methods not being called.
i can't head around , tried debug, no avail. tell me reason, or give me ideas debug appreciated. thanks!
edit: when assign datasource = self
after init
stage, works well. rather in init
phase. how can make work during init
?
from uicollectionviewconrtoller
docs:
when loading collection view storyboard or nib file, data source , delegate objects collection view obtained nib file. if data source or delegate not specified, collection view controller assigns itself unspecified role.
so if use uicollectionviewconrtoller
need reassign datasource custom collection view.
Comments
Post a Comment