在使用新浪微博APP时,我们发现新浪微博iOS客户端导航栏item点击会有高亮效果,图片和字体颜色是可以像UIButton那样变化的。明显这不是系统自带的效果,需要我们自定义UIBarButtonItem。简要的贴一下代码:
/**
* 只有title
*/
+ (UIBarButtonItem *)itemWithLeftTitle:(NSString *)title target:(id)target action:(SEL)action color:(UIColor *)color highlightedColor:(UIColor *)highlightedColor
{
UIButton *btn = [self buttonWithTitle:title target:target action:action color:color highlightedColor:highlightedColor image:nil highlightedImage:nil];
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btn.titleEdgeInsets = UIEdgeInsetsMake(0, -8, 0, 0);
return [[UIBarButtonItem alloc] initWithCustomView:btn];
}
+ (UIBarButtonItem *)itemWithRightTitle:(NSString *)title target:(id)target action:(SEL)action color:(UIColor *)color highlightedColor:(UIColor *)highlightedColor
{
UIButton *btn = [self buttonWithTitle:title target:target action:action color:color highlightedColor:highlightedColor image:nil highlightedImage:nil];
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
btn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -8);
return [[UIBarButtonItem alloc] initWithCustomView:btn];
}
设置title为什么要写两个方法呢,原因是leftBarButtonItem和rightBarButtonItem显示的位置是不同的。如果不设置titleEdgeInsets,那么显示的位置和原生UIBarButtonItem会有区别。leftBarButtonItem设置它的titleEdgeInsets向左偏移8个像素点。rightBarButtonItem设置它的titleEdgeInsets向右偏移8个像素点。这样和自带的BarButtonItem位置基本相同。
如下图所示: