ios - UICollectionViewCell and UIScrollView -
i encountered weird behavior of uiscrollview when inside uicollectionviewcell. in project have collectionview , each cell has uiscrollview contains 1 or more images. here's sample code purpose of question:
- (uicollectionviewcell *)collectionview:(uicollectionview *)cv cellforitematindexpath:(nsindexpath *)indexpath { customcollectioncell * cell = [cv dequeuereusablecellwithreuseidentifier:@"customcell" forindexpath:indexpath]; uiimageview * imageview = [[uiimageview alloc] initwithframe:cgrectmake(20, 20, 150, 150)]; imageview.image = [uiimage imagenamed:@"someimage.png"]; [cell.scrollview addsubview:imageview]; return cell; }
of course in project it's not same image different ones fed database.
the first collection cell added no problem. when add second cell, scrollview seems duplicate , place instance of on top. know sounds weird, can see how looks in image below:
notice how image in scrollview on left has darkened, assume it's because scrollview duplicated.
so, i'm guessing cell reused in wrong way or something.
thanks help!
a new uiimageview
being added reused cell each time collectionview: cellforitematindexpath:
invoked. solve this, in custom uicollectionviewcell
, implement prepareforreuse
method. in method, remove image view.
to accomplish this, set tag on image view. e.g.,:
(uicollectionviewcell *)collectionview:(uicollectionview *)cv cellforitematindexpath:(nsindexpath *)indexpath { customcollectioncell * cell = [cv dequeuereusablecellwithreuseidentifier:@"customcell" forindexpath:indexpath]; uiimageview * imageview = [[uiimageview alloc] initwithframe:cgrectmake(20, 20, 150, 150)]; imageview.image = [uiimage imagenamed:@"someimage.png"]; [cell.scrollview addsubview:imageview]; // following line of code new cell.contentview.tag = 100; return cell; }
and remove image view cell, add/update prepareforreuse
method in custom cell:
-(void)prepareforreuse{ uiview *myimageview = [self.contentview viewwithtag:100]; [myimageview removefromsuperview]; }
Comments
Post a Comment