在iOS7以上,个人感觉UIBarButtonItem在NavigationBar上太靠左和太靠右
如图,想在两个箭头之处,间隔屏幕的间距更大一些,所以分享出来自定义UIBarButtonItem
首先创建一个UIBarButtonItem的category
//继承的UIButton 改变间距
@interface GSBarButton : UIButton
@end
@interface UIBarButtonItem (HSBarButton)
+ (instancetype)backBarButtonItemWithTarget:(id)target action:(SEL)action;//自定义的后退键 左边键
+ (instancetype)cancelBarButtonItemWithTarget:(id)target action:(SEL)action;//取消按钮 左边的
//还可以定义一些其他的需要的方法
//两个基础的创建UIBarButtonItem方法
- (instancetype)initWithTitle:(NSString *)title target:(id)target action:(SEL)action;
- (instancetype)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage target:(id)target action:(SEL)action;
@end
.m文件
@implementation HSBarButton
//改变间距
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
CGRect bounds = self.bounds;
CGFloat widthDelta = MAX(44.0 - bounds.size.width, 0);
CGFloat heightDelta = MAX(44.0 - bounds.size.height, 0);
bounds = CGRectInset(bounds, -0.5 * widthDelta, -0.5 * heightDelta);
return CGRectContainsPoint(bounds, point);
}
@end
@implementation UIBarButtonItem (HSBarButton)
+ (instancetype)backBarButtonItemWithTarget:(id)target action:(SEL)action
{
return [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:KLeftBarButtonImage] style:UIBarButtonItemStylePlain target:target action:action];
}
+ (instancetype)cancelBarButtonItemWithTarget:(id)target action:(SEL)action
{
return [[self alloc] initWithTitle:@"取消" target:target action:action];
}
- (instancetype)initWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
HSBarButton *button = [[HSBarButton alloc] init];
[button setTitle:title forState:UIControlStateNormal];
[button setTitle:title forState:UIControlStateHighlighted];
[button setTitleColor:kGSNavigationTitleColor forState:UIControlStateNormal];
[button setTitleColor:kGSBaseHighlightedColor forState:UIControlStateHighlighted];
[button setTitleColor:[kGSNavigationTitleColor colorWithAlphaComponent:0.5] forState:UIControlStateDisabled];
button.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
[button sizeToFit];
self = [self initWithCustomView:button];
if (self)
{
}
return self;
}
- (instancetype)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage target:(id)target action:(SEL)action
{
HSBarButton *button = [[HSBarButton alloc] init];
[button setImage:image forState:UIControlStateNormal];
[button setImage:highlightedImage forState:UIControlStateHighlighted];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
[button sizeToFit];
self = [self initWithCustomView:button];
if (self)
{
}
return self;
}
@end
这样 就搞定,有什么不对的地方 望请指教,一起学习