简体   繁体   中英

Pass self.navigationController as a parameter in addTarget for UIbutton

I have programatically added a UIButton , for which I require addTarget . The selector action is in another class. I have used the following code to do this.

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");
}

This works just fine. But I need to use pushViewController in the class function for which I need to pass the self.navigationController to the function.

I tried using homeBtn.nav = self.navigationController; but this gives an error 'Property nav not found on object of type UIButton *'

Can anyone please help me and tell me how to pass the self.navigationController to the class function.

Regards,

Neha

Unfortunately, this is not possible. You are creating static (aka class ) methods, this is indicated by the + in front of the method name +(void)ButtonTapped:(id)sender . In these methods you can not access instance variables or properties of the objects, since they are called on a class and not on an object.

Instead of making everything static, maybe try to create instance regular methods for what you want to achieve. An example could be:

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

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

Here, myObject should be an instance of the class myClass .

Having this, you are allowed to access instance variables of the object that invokes the ButtonTapped method, so then you are allowed to use self.navigationController .

PS. Naming conventions in iOS are such that you start method names with lowercase letters and class names with uppercase letters, so for you it would be MyClass and -(void)buttonTapped .

If you want to be able to use the following line:

homeBtn.nav = self.navigationController;

You can subclass UIButton and add the property to it.

@interface CustomButton : UIButton

@property (strong, nonatomic) UINavigationController *nav;

@end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM