UICollectionView中每个UIButton的特定操作

时间:2014-07-01 20:37:50

标签: ios objective-c uibutton

我有4个UICollectionCell(名为CustomCell),每个包含一个按钮。每个按钮必须具有不同的行为。我设法通过使用NSArray(感谢stackOverflow!)并设置不同的字体和选择器来做到这一点,但我觉得必须有一种更简单的方法,我没有找到。

这是我的代码:

#import "MainViewController.h"
#import "customCell.h"

@interface MainViewController ()

@end

@implementation MainViewController
{
    NSArray * arrayOfImg;
    NSArray * arrayOfMethods;

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[self myCollectionView]setDataSource:self];
    [[self myCollectionView]setDelegate:self];

    arrayOfImg = @[NSArray arrayWithObjects:@"note_button", @"photo_button", @"sync_agenda_button", @"sync_contacts_button", nil];

    arrayOfMethods = @[@"showText", @"showText2", @"showText3", @"showText4"];

}

-(void)showText
{
    NSLog(@"text1!");
}

-(void)showText2
{
    NSLog(@"text2");
}

-(void)showText3
{
    NSLog(@"text3");
}

-(void)showText4
{
    NSLog(@"text4");
}

#pragma mark CollectionView methods

- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}

这是我设置不同行为的地方:

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    customCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

    [cell.myButton setBackgroundImage:[UIImage imageNamed:[arrayOfImg objectAtIndex:indexPath.item]] forState:UIControlStateNormal];

    SEL selector = NSSelectorFromString([arrayOfMethods objectAtIndex:indexPath.item]);
    [cell.myButton addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

@end

0 个答案:

没有答案