README and documentationshow my code:
- (NSInteger)numberOfItems{
return self.data.count;
}
- (CGSize)sizeForItemAtIndex:(NSInteger)index {
CGFloat width = ([self.collectionContext containerSize].width - self.minimumLineSpacing * 5) / 4;
return CGSizeMake(width, width);
}
- (__kindof UICollectionViewCell *)cellForItemAtIndex:(NSInteger)index{
UICollectionViewCell *cell = [self.collectionContext
dequeueReusableCellOfClass:[UICollectionViewCell class]
forSectionController:self
atIndex:index];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
// my settings...
[btn addTarget:self action:@selector(didClickbutton:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn];
[btn mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.mas_equalTo(cell.contentView);
}];
return cell;
}
- (void)didSelectItemAtIndex:(NSInteger)index{
NSLog(@"item %@ clicked", self.data[index]);
}
- (void)didClickButton:(UIButton *)button {
// what's the index ???
}
If I didn't add button to the cell, the didSelectItemAtIndex: will fire, and if I put a button in it, can't.
Sure I can use plain text and image in cell, but first, it's lack of highlight effect, second, why can't I add a button? or how can I click a button and get the index of the button
@walkerwzy you could either disable the userInteraction on the button or just set the tag value of the button to the index (mind that this can change after removing or adding objects)
I feel your desired effect is something similiar to the "Empty View Controller" demo we have in the example pack. Where the individual cells have buttons, but the effect of the button wants to be received from the section controller. Maybe take a look at that example for a bit of guidance on this.
Either way in the section controller class you can access the collection context (self.collectionContext) of which has a method on it index(forCell cell: Any!, sectionController: Any!) -> Any!. By passing the cell the button is in, and self for the section controller you will in turn receive the index.
Echoing @Sherlouk, would definitely look at the examples. I would avoid adding the button to your cell in cellForItemAtIndex: and instead the cell should own the button, add itself as the target/action, and use a delegate of the cell to receive events about button taps.
FWIW the button in that example does not trigger didSelectItemAtIndex:.
@MarvinNazari yes, tag could be a straightforward way.
and I missed the EmptyViewController example, and yes, delegate it's also a way.
though neither of these trigger didSelectItemAtIndex:, but it's not necessary if I can get index from my event handler.
Most helpful comment
@walkerwzy you could either disable the
userInteractionon the button or just set thetagvalue of the button to the index (mind that this can change after removing or adding objects)