另一个班级中的操作按钮?

时间:2015-08-28 14:19:55

标签: ios ibaction

我有这个类来创建带按钮的导航栏:

NavigationBar.m
+ (void)styleNavBar :(UIView*) view withColor:(UIColor*)color {
// 1. hide the existing nav bar
//[self.navigationController setNavigationBarHidden:YES animated:NO];

// 2. create a new nav bar and style it
UINavigationBar *newNavBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 20.0, CGRectGetWidth(view.bounds), 44.0)];
newNavBar.barTintColor = color;
//newNavBar.shadowImage = nil;


// 3. add a new navigation item w/title to the new nav bar
UINavigationItem *newItem = [[UINavigationItem alloc] init];
//newItem.title = @"AmisViewController";

UIBarButtonItem *myAddButton  = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(myAddAction:)];
UIBarButtonItem *myCoolButton = [[UIBarButtonItem alloc] initWithTitle:@"Cool!" style:UIBarButtonItemStyleDone target:self action:@selector(myCoolAction:)];

NSArray *myButtonArray = [[NSArray alloc] initWithObjects:myCoolButton, myAddButton, nil];

newItem.leftBarButtonItems = myButtonArray;

[newNavBar setItems:@[newItem]];
// 4. add the nav bar to the main view
[view addSubview:newNavBar];
}

和2个事件:

-(IBAction)myAddAction:(id)sender{
NSLog(@"myAddButton");
}
-(IBAction)myCoolAction:(id)sender{
NSLog(@"myCoolButton");
}

我的问题是当我在viewcontrollers中调用我的方法styleNavBar时,我的应用程序崩溃+[NavigationBar myCoolAction:]: unrecognized selector sent to class 我的问题是如何添加方法myAddAction和myCoolButton?

1 个答案:

答案 0 :(得分:0)

问题是您在NavigationBar中创建了一个按钮,而NavigationBar并不知道一个名为myCoolAction的方法。

话虽这么说,最好不使用按钮设置导航栏的样式,然后在视图控制器中添加按钮。现在,您可以将目标设置为视图控制器,并将myCoolAction添加到视图控制器。

另一个解决方案是protocol / delegate。