IOS全局修改NavigateBar Back Button樣式的兩種方法:
1筷畦,通過[UIBarButtonItem appearance] 的setBackButtonBackgroundImage方法對back按鈕樣式自定義 但是此方法中設置forState:UIControlStateHighlighted屬性無效 設置圖片的imageWithRenderingMode阻止系統(tǒng)渲染也沒有用(如有錯誤還望指正)
2冠骄,通過自定義NavigationController 重寫push方法實現(xiàn)對back按鈕的全局修改 當需要在局部控制器設置back 按鈕樣式時 直接可以覆蓋 (推薦此方法)
下面是兩種方法的具體實現(xiàn)
1穆刻,
UIImage*backButtonBackgroundImage = [UIImageimageNamed:@"navigationbar_back"];
UIImage*backButtonBackgroundImageSelected =[UIImageimageNamed:@"navigationbar_back_highlighted"];
backButtonBackgroundImage = [backButtonBackgroundImageresizableImageWithCapInsets:UIEdgeInsetsMake(0,backButtonBackgroundImage.size.width-1,0,0)];
//設置全局屬性
idappearance = [UIBarButtonItem appearance];
[appearancesetBackButtonBackgroundImage:backButtonBackgroundImage forState:UIControlStateNormalbarMetrics:UIBarMetricsDefault];
[appearance setBackButtonBackgroundImage:backButtonBackgroundImageSelected forState:UIControlStateHighlighted bar Metrics:UIBarMetricsDefault];
//將文字隱藏
[appearance setTitleTextAttributes:@{
NSFontAttributeName:[UIFontsystemFontOfSize:0.1],
NSForegroundColorAttributeName: [UIColorclearColor]
}
forState:UIControlStateNormal];
2(推薦此方法)
//首先創(chuàng)建自定義UICustomNavigationController 繼承系統(tǒng)的UINavigationController
//重寫UICustomNavigationController 的 -(void)pushViewController:(UIViewController*)viewController animated:(BOOL)animated 方法:
@implementation UICustomNavigationController
-(void)pushViewController:(UIViewController*)viewController animated:(BOOL)animated{
[superpushViewController:viewControlleranimated:animated];
//NavigationController中包含的第一個UIViewController也是push方法進來的 但是一般這個controller不需要添加back button?
if(self.viewControllers.count>1) {
UIButton*backButton=[UIButtonbuttonWithType:UIButtonTypeCustom];
[backButtonsetBackgroundImage:[UIImageimageNamed:@"navigationbar_back"]forState:UIControlStateNormal];
[backButtonsetBackgroundImage:[UIImageimageNamed:@"navigationbar_back_highlighted"]forState:UIControlStateHighlighted];
backButton.frame=CGRectMake(0,0,30,30);
[backButtonaddTarget:selfaction:@selector(back)forControlEvents:UIControlEventTouchUpInside];
viewController.navigationItem.leftBarButtonItem=[[UIBarButtonItemalloc]initWithCustomView:backButton];
}
}
//back方法
-(void)back{
[self popViewControllerAnimated:YES];
}
@end
最后創(chuàng)建自定義Back 按鈕的UICustomNavigationController
UICustomNavigationController*navVc=[[UICustomNavigationController alloc] ?initWithRootViewController:childViewController];