【问题标题】:Pass self.navigationController as a parameter in addTarget for UIbutton将 self.navigationController 作为参数传递给 UIbutton 的 addTarget
【发布时间】:2014-03-19 07:48:14
【问题描述】:

我以编程方式添加了一个UIButton,为此我需要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");
}

这很好用。但我需要在需要将self.navigationController 传递给函数的类函数中使用pushViewController

我尝试使用homeBtn.nav = self.navigationController; 但这会产生错误'Property nav not found on object of type UIButton *'

谁能帮助我,告诉我如何将self.navigationController 传递给类函数。

问候,

内哈

【问题讨论】:

标签: ios objective-c


【解决方案1】:

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

不要让一切都变成静态的,也许可以尝试为您想要实现的目标创建实例常规方法。一个例子可能是:

[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

【讨论】:

    【解决方案2】:

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

    homeBtn.nav = self.navigationController;
    

    您可以继承 UIButton 并向其添加属性。

    @interface CustomButton : UIButton
    
    @property (strong, nonatomic) UINavigationController *nav;
    
    @end
    

    【讨论】:

      猜你喜欢
      • 2018-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      相关资源
      最近更新 更多