[IOS]navigation bar自定义按钮

1.建立Category类:

.h:

@interface UIViewController (SMHNavigationBar)

- (void)customLeftButton:(NSString*)leftImageName;
- (void)onCustomLeftButtonClick:(id)sender;

@end

 .m:

#define screenWidth [UIScreen mainScreen].bounds.size.width

@implementation UIViewController (SMHNavigationBar)

- (void)customLeftButton:(NSString*)leftImageName{
    UIImage *leftImage = [UIImage imageNamed:leftImageName];
    
    UIButton *navButton = [UIButton buttonWithType:UIButtonTypeCustom];
    if (leftImage != nil) {
        [navButton setImage:leftImage forState:UIControlStateNormal];
    }
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 65, 33)];
    [navButton addTarget:self action:@selector(onCustomLeftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        if(screenWidth >= 414){
            navButton.frame = CGRectMake((screenWidth/61)*3-17, 0, 36, 36);
    
        }else{
            navButton.frame = CGRectMake((screenWidth/61)*3-14, 0, 36, 36);
        }
    
    [leftView addSubview:navButton];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];
}

- (void)onCustomLeftButtonClick:(id)sender{
    
}
@end

使用:

 [self customLeftButton:@"list2"];

*隐藏回退键:

self.navigationItem.hidesBackButton = YES;

猜你喜欢

转载自jameskaron.iteye.com/blog/2398625