之前有很多项目中需要对backBarButtonItem定制,使用了很多种方法,也走了很多弯路。
第一种:
刚开始对整体不是很熟悉,直接在当前ctl里面使用下列代码进行定制:
1 UIButton * testButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)]; 2 [testButton setBackgroundImage:[UIImage imageNamed:@"test"] forState:UIControlStateNormal]; 3 [testButton setBackgroundImage:[UIImage imageNamed:@"test1"] forState:UIControlStateHighlighted]; 4 5 UIBarButtonItem * backBarButton = [[UIBarButtonItem alloc] initWithCustomView:testButton]; 6 self.navigationItem.backBarButtonItem = backBarButton;
但是毫无效果,后来了解到是两个问题导致:1、当前backBarButtonItem应该在UINavigationController的栈中当前ctl的上一级ctl中生成。
2、backBarButtonItem 如果使用- (id)initWithCustomView:(UIView *)customView;生成是不会有效果的。
由于只能使用其他的方法初始化,不能很好的定制,所以有局限性。
后来网上搜索,发现最常见的解决方案是对当前的ctl的leftBarButtonItem进行定制。
第二种:
UIButton * testButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)]; [testButton setBackgroundImage:[UIImage imageNamed:@"test"] forState:UIControlStateNormal]; [testButton setBackgroundImage:[UIImage imageNamed:@"test1"] forState:UIControlStateHighlighted]; UIBarButtonItem * backBarButton = [[UIBarButtonItem alloc] initWithCustomView:testButton]; self.navigationItem.leftBarButtonItem = backBarButton;
这种方法可以对当前ctl的backBarButtonItem进行比较好的定制。后来有需求要把backBarButtonItem做成系统一样的风格,但是又要改变那个返回的小箭头图标,说是箭头太粗。 由于backBarButtonItem的标题会变化,本想定制一个UIButton,根据返回图标和标题布局,但是做起来又觉得麻烦,后来想到了很好用的方法3
第三种:
//注意图片边缘要做成透明的,方便拉升
UIImage *backButtonBackgroundImage = [UIImage imageNamed:@"nav_back_button_normal"];
// The background should be pinned to the left and not stretch.
backButtonBackgroundImage = [backButtonBackgroundImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, backButtonBackgroundImage.size.width - 1, 0, 0)];
//定义你想在哪些类中使用这个效果
id appearance = [UIBarButtonItemappearanceWhenContainedIn:[UINavigationControllerclass], nil];
[appearance setBackButtonBackgroundImage:backButtonBackgroundImage forState:UIControlStateNormalbarMetrics:UIBarMetricsDefault];
// Provide an empty backBarButton to hide the 'Back' text present by
// default in the back button.
//
// NOTE: You do not need to provide a target or action. These are set
// by the navigation bar.
// NOTE: Setting the title of this bar button item to ' ' (space) works
// around a bug in iOS 7.0.x where the background image would be
// horizontally compressed if the back button title is empty.
UIBarButtonItem *backBarButton = [[UIBarButtonItemalloc] initWithTitle:@"测试"style:UIBarButtonItemStylePlaintarget:nilaction:NULL];
self.navigationItem.backBarButtonItem = backBarButton;
这个是从Apple官方的Demo里面找到的,直接用图标替换掉就OK。不要做其他麻烦事情。