Ios 将self.navigationController作为参数传递给UIbutton的addTarget
我已通过编程方式添加了一个Ios 将self.navigationController作为参数传递给UIbutton的addTarget,ios,objective-c,Ios,Objective C,我已通过编程方式添加了一个ui按钮,为此我需要addTarget。选择器操作位于另一个类中。我使用了以下代码来实现这一点 UIButton *homeBtn = [[UIButton alloc] initWithFrame:CGRectMake(10,5,32,32)]; homeBtn.backgroundColor = [UIColor greenColor]; [homeBtn addTarget:[myClass class] action:@selector(ButtonTapped
ui按钮
,为此我需要addTarget
。选择器操作位于另一个类中。我使用了以下代码来实现这一点
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代码>
但这会导致错误“在UIButton*类型的对象上找不到属性nav”
任何人都可以帮助我并告诉我如何将self.navigationController
传递给类函数
问候,
Neha不幸的是,这是不可能的。您正在创建静态(aka类)方法,这由方法名称
+(void)按钮前面的+
指示,该按钮标记为:(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
注:iOS中的命名约定是,方法名以小写字母开头,类名以大写字母开头,因此,如果您希望能够使用以下行,则可以使用
MyClass
和-(void)按钮:
homeBtn.nav = self.navigationController;
您可以将UIButton子类化并向其添加属性
@interface CustomButton : UIButton
@property (strong, nonatomic) UINavigationController *nav;
@end