0

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

Mohammad Ashfaq
  • 1,333
  • 2
  • 14
  • 38
Neha Dangui
  • 597
  • 2
  • 13
  • 28

2 Answers2

0

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.

nburk
  • 22,409
  • 18
  • 87
  • 132
0

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
ZeMoon
  • 20,054
  • 5
  • 57
  • 98