如何为UIButton传递目标参数?

时间:2014-08-26 07:49:28

标签: ios objective-c uibutton

我在UIView+Extensions.m中写了一个类别方法:

@interface UIView (Extensions)
+ (UIView*)configureMoreViewWithBtns:(NSArray*)btnsConf;
@end

+ (UIView*)configureMoreViewWithBtns:(NSArray*)btnsConf
{
    UIView* moreView = [[self alloc] initWithFrame:CGRectMake(195, 180, 120, 100)];
    [moreView setBackgroundColor:[UIColor lightGrayColor]];
    for (int i = 0; i < btns.count; i++) {
        NSDictionary* confDict = btnsConf[i];

        UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake(0, i*30 + 10, 120, 20)];
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [btn setTitle:confDict[@"title"] forState:UIControlStateNormal];
        [btn addTarget:self 
                action:NSSelectorFromString(confDict[@"selector"] 
    forControlEvents:UIControlEventTouchUpInside];
        [moreView addSubView:btn];
    }
    return moreView;
}

但是这个工具是错误的,因为我不知道如何从我的ViewController传递target参数?

在我的viewController中,我这样调用了这个方法:

- (void)handleMoreImageTapped:(UITapGestureRecognizer*)gestureRecognizer
{
    NSLog(@"%s", __FUNCTION__);
    UITableViewCell* tappedCell = [UIView tableViewCellFromTapGestture:gestureRecognizer];

    NSArray* btnsConf = @[
        @{@"title": @"分享", @"selector": NSStringFromSelector(@selector(handleShare:))},
        @{@"title": @"私信", @"selector": NSStringFromSelector(@selector(handleSiXin:))},
        @{@"title": @"举报或屏蔽", @"selector": NSStringFromSelector(@selector(handleJuBao:))}
                         ];  
    UIView* moreView = [UIView configureMoreViewWithBtns:btnsConf];    
}

1 个答案:

答案 0 :(得分:2)

您还需要在dictionairies中传递目标(将调用选择器的对象,在本例中为调用configuremoreviewwithbtns方法的viewcontroller)。 因此,添加到数组中的字典将成为

@{@"title": @"thetitle", @"selector": NSStringFromSelector(@selector(theselector:)), @"target": self},

并且您必须将UIView扩展名更改为:

[btn addTarget:confDict[@"target"]
            action:NSSelectorFromString(confDict[@"selector"] 
forControlEvents:UIControlEventTouchUpInside];