我正在创建一个自定义导航按钮,而不是它的默认外观。我能够创建按钮,但我遇到的问题是它的选择器。我想在不同类的方法中添加该按钮的选择器。我将UIViewController作为参数传递,因此我可以修改navigationBar。
-(void)addNavButton:(MyViewController *)vc
{
UIImage *buttonImg = [UIImage imageNamed:@"back.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImg forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, buttonImg.size.width, buttonImg.size.height);
[button addTarget:self action:@selector(vc.popBackNavigation) forControlEvents:UIControlEventTouchUpInside]; //Here is the line where I am having trouble
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
vc.navigationItem.leftBarButtonItem = customBarItem;
}
我这样做是因为我不想在每个类中添加相同的方法来定义customNavigation项。如果有一个简短的方法或有效的方法,请告诉我
答案 0 :(得分:1)
在这种情况下,你需要针对不同的类。
请记住,目标是您要将邮件发送到的对象。所以在这种情况下,选择器是:
@selector(popBackNavigation)
,目标是vc
。
,并提供:
[button addTarget:vc action:@selector(popBackNavigation) forControlEvents:UIControlEventTouchUpInside];
答案 1 :(得分:1)
希望您正在寻找类似的东西:
@implementation Utility
+ (UIBarButtonItem *)addNavButton:(id)target withSelector:(SEL)selectorMethod
{
UIImage *buttonImg = [UIImage imageNamed:@"back.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImg forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, buttonImg.size.width, buttonImg.size.height);
[button addTarget:target action:selectorMethod forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
return customBarItem;
}
@end
从viewController中调用此方法,
@implementation Mycontroller
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *leftItem = [Utility addNavButton:self withSelector:@selector(backbuttonAction)];
self.navigationItem.leftBarButtonItem = leftItem;
}
@end
答案 2 :(得分:1)
如果您想在应用中自定义此后退按钮,可以将此代码放入AppDelegate
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options
{
UIImage *buttonImg = [UIImage imageNamed:@"back.png"];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:buttonImg forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
// customize the position if needed
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, buttonImg.size.height*2) forBarMetrics:UIBarMetricsDefault];
return yes;
}
如果没有任何进一步的互动,这将覆盖您应用的默认后退按钮样式。