2014-03-19 51 views
0

我编程式地添加了一个UIButton,对此我需要addTarget。选择器动作在另一个类中。我已经使用下面的代码来做到这一点。将self.navigationController作为addTarget中的参数传递给UIbutton

UIButton *homeBtn = [[UIButton alloc] initWithFrame:CGRectMake(10,5,32,32)]; 
homeBtn.backgroundColor = [UIColor greenColor]; 
[homeBtn addTarget:[myClass class] action:@selector(ButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubView:homeBtn]; 

+(void)ButtonTapped:(id)sender{ 
    NSLog(@"here"); 
} 

这工作得很好。但我需要在类函数中使用pushViewController,因此我需要将self.navigationController传递给函数。

我尝试使用homeBtn.nav = self.navigationController; 但是这给出了一个错误'Property nav not found on object of type UIButton *'

任何人都可以请帮助我,告诉我如何将self.navigationController传递给类函数。

问候,

NEHA

+0

http://stackoverflow.com/questions/3716633/passing-parameters-on-button-actionselector –

回答

0

不幸的是,这是不可能的。您正在创建静态(又名类别)方法,这由方法名称+(void)ButtonTapped:(id)sender前面的+表示。在这些方法中,您无法访问对象的实例变量或属性,因为它们是在上调用的,而不是在对象上调用的。

而不是将所有内容都设置为静态,也许可以尝试创建实例常规方法以获得所需内容。一个例子可以是:

[homeBtn addTarget:myObject action:@selector(ButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubView:homeBtn]; 

-(void)ButtonTapped:(id)sender{ 
    NSLog(@"here"); 
} 

这里,myObject应该是类myClass的一个实例。

这样,您就可以访问调用ButtonTapped方法的对象的实例变量,因此您可以使用self.navigationController

PS。 iOS中的命名约定是这样的,你可以使用小写字母和带有大写字母的类名来启动方法名,因此对于你来说,它将是MyClass-(void)buttonTapped

0

如果你希望能够使用以下行:

homeBtn.nav = self.navigationController; 

你也可以继承的UIButton和属性添加到它。

@interface CustomButton : UIButton 

@property (strong, nonatomic) UINavigationController *nav; 

@end 
相关问题