Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/122.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 将self.navigationController作为参数传递给UIbutton的addTarget_Ios_Objective C - Fatal编程技术网

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