2011-03-17 107 views
0

我试图编写一个方便的方法,返回一个UIButton并将标题,CGRect和一个操作作为参数。我的代码编译并运行,但当我实际单击按钮时崩溃。问题传递方法作为参数

这里是我的简便方法:

+ (UIButton *)makeButton:(NSString *)title withRect:(CGRect)rect 
     withAction:(SEL)selectorX { 

    // setup button properties 
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; 
    btn.frame = rect; 
    [btn setFont:[UIFont boldSystemFontOfSize:20]]; 
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter; 
    btn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 
    [btn setBackgroundImage:[[UIImage imageNamed:@"btn_21.png"] 
     stretchableImageWithLeftCapWidth:10.0                      
     topCapHeight:0.0] forState:UIControlStateNormal]; 
    [btn setTitle:@"TEST" forState:UIControlStateNormal]; 
    [btn addTarget:self action:@selector(selectorX:) 
     forControlEvents:UIControlEventTouchUpInside]; 

    return btn; 
} 

这里是我怎样,我称之为:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    btn = [Utilities makeButton:@"TEST" withRect:CGRectMake(10, 100, 236, 45) 
      withAction:@selector(buttonActionTEST:)]; 
    [self.view addSubview:btn]; 
} 

- (void) buttonActionTEST:(id)sender { 

    [Utilities alert:@"yo yo yeoman"]; 

} 

回答

1

您需要同时提供目标选择器以调用该目标。你只是提供了选择,然后做到这一点:

[btn addTarget:self action:@selector(selectorX:) 
    forControlEvents:UIControlEventTouchUpInside]; 

这是不对的两个帐户:第一,在这种情况下计算的类Utilities(甚至不是一个实例,但Class对象) 。然后,当您传递硬编码选择器selectorX:而不是具有几乎相同名称的变量时,尝试提供选择器也是错误的。它应该做的事是这样的:

+ (UIButton *)makeButton:(NSString *)title withRect:(CGRect)rect 
     target:(id)aTarget action:(SEL)anAction { 
... 
    [btn addTarget:aTarget action:anAction 
     forControlEvents:UIControlEventTouchUpInside]; 
... 
} 

然后调用它像这样:

btn = [Utilities makeButton:@"TEST" withRect:CGRectMake(10, 100, 236, 45) 
     target:self action:@selector(buttonActionTEST:)]; 
0

你方便的方法已经采取选择作为一个参数 - 这是一个真正的选择器,所以靠近该方法的底部使用:

[btn addTarget:self action:selectorX forControlEvents:UIControlEventTouchUpInside]; 

(无需将selectorX包装在@selector()中,因为它选择器)。

0

我认为这个问题是从线来:

[btn addTarget:self action:@selector(selectorX:)  forControlEvents:UIControlEventTouchUpInside]; 

不会“自我“有公用事业类吗?另外我不认为你需要@选择器。