io ti do il codice completo di come avrei fatto ciò che si desidera eseguire:
Prima di tutto, creare una sottoclasse di UICollectionViewCell. Chiamiamola CustomCell e assegnagli una proprietà pubblica UIButton chiamata deleteButton. Poi, in CustomCell.m:
#define delButtonSize 60
// Lazy load the deleteButton
- (UIButton *)deleteButton
{
if (!_deleteButton)
{
_deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, delButtonSize, delButtonSize)];
_deleteButton.center = CGPointMake(9, 10);
_deleteButton.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:_deleteButton];
[_deleteButton addTarget:self action:@selector(deleteRecipe) forControlEvents:UIControlEventTouchUpInside];
}
return _deleteButton;
}
// Here we remove all the custom stuff that we added to our subclassed cell
- (void) prepareForReuse
{
[super prepareForReuse];
[self.deleteButton removeFromSuperview];
self.deleteButton = nil;
}
- (void) deleteRecipe
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"DeleteCell" object:self];
}
Ora nel tuo ViewController, fare questo:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
//[cell.deleteButton setImage: [UIImage imageNamed:@"cross_30.png"] forState:UIControlStateNormal];
[cell.deleteButton setBackgroundColor:[UIColor blueColor]];
cell.contentView.backgroundColor = [UIColor redColor];
return cell;
}
- (void) deleteCell:(NSNotification *)notification
{
NSIndexPath *indexPath = [self.collectionView indexPathForCell:(CustomCell *)notification.object];
[self.contentData removeObjectAtIndex:indexPath.row];
[self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
}
ho provato il mio codice, ha funzionato perfettamente sul mio computer. Spero che aiuti!
tenta di eseguire il debug di set '_deleteButton.backgroundColor = [UIColor redColor];' E rimuovi questa riga '_deleteButton.center = CGPointMake (9, 10);' – anhtu
E dove gestisci '_deleteButton'? – anhtu
cosa intendi per .. "Sono in grado di aggiungere il pulsante in alto a sinistra della cella ma non appare sopra la cella ma sotto la cella", per favore fornisci ulteriori dettagli ... –