导航条按钮的间距问题
2016-07-20 本文已影响293人
oncezou
需求:自定义导航条右边按钮的间距
问题:系统导航条rightBarButtonItem默认与右边有30*UI_RATE的间距(UI_RATE是适配比率)
解决如下:封装一个方法
+ (NSArray *)initRightBarButtonItemsWithTarget:(id)target action:(SEL)action title:(NSString *)title font:(CGFloat)font titleColorNormal:(UIColor *)titleColorNormal titleColorHightLight:(UIColor *)titleColorHightLight
{
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:fontSize];
if(titleColorNormal){
[button setTitleColor:titleColorNormal forState:UIControlStateNormal];
}
if(titleColorHightLight){
[button setTitleColor:titleColorHightLight forState:UIControlStateNormal];
}
//设置按钮的frame
/*
*[NSString calculateTextWidth:title font:[UIFont systemFontOfSize:fontSize]]是计算文章的宽度
*48*UI_RATE是自定义的间距,因为文字是居中的,所以左右间距是24*UI_RATE
*/
[button setFrame:CGRectMake(0, 0,48 * UI_RATE + [NSString calculateTextWidth:title font:[UIFont systemFontOfSize:fontSize]], 40)];
//添加一个占位UIBarButtonItem来代替那30 * UI_RATE的留白间距
UIBarButtonItem * negativeSpacer = [[ UIBarButtonItem alloc ] initWithBarButtonSystemItem : UIBarButtonSystemItemFixedSpace target:nil action:nil];
//设置width为-30 * UI_RATE相当于往右偏移-30 * UI_RATE
negativeSpacer.width = -30 * UI_RATE;
UIBarButtonItem * buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
//顺序不能换(rightBarButtonItems界面的展示是从最右边从第一个依次向左摆放)
return @[negativeSpacer,buttonItem];
}
self.navigationItem.rightBarButtonItems = [UIBarButtonItem initRightBarButtonItemsWithTarget:self action:@selector(sureAction:) title:@"确定" font:0 titleColorNormal:nil titleColorHightLight:nil];
导航条左边leftBarButtonItems同理:leftBarButtonItems界面的展示是从最左边边从第一个依次向右摆放