功能描述:提供导航标题,左右按钮及点击功能。
做法
新建一个类,继承自UIView。
在.h文件中提供外界创建方法,标题颜色属性
@interface PDtopBar : UIView
@property(nonatomic,strong)UIColor *titleColor;
@property(nonatomic,strong)UIColor *viewColor; // 背景色
@property(nonatomic,assign)BOOL hidden; //隐藏?
@property(nonatomic,strong)void(^gobackBlock)(); // 返回上一页block
@property(nonatomic,strong)void(^clickRightBtnBlock)(); // 点击右按钮block
// 提供外界创建方法
-(instancetype)initWithTitle:(NSString *)title rightBtnTitle:(NSString *)rightText;
@end
.m文件中,声明子控件
@interface PDtopBar()
@property(nonatomic,weak)UILabel *topTitleLabel; // 标题
@property(nonatomic,weak)UIButton *backBtn; // 左边的返回按钮
@property(nonatomic,weak)UIButton *rightBtn; // 右边的按钮
@end
实现创建方法
-(instancetype)initWithTitle:(NSString *)title rightBtnTitle:(NSString *)rightText{
if(self = [super init]){
self.backgroundColor = [UIColor whiteColor];
//位置,尺寸
self.frame = CGRectMake(0, 20, screenW, 44);
if(screenH == 812)
self.frame = CGRectMake(0, 44, screenW, 44); // 适配IphoneX
UILabel *toplabel = [[UILabel alloc] Label_color3:Font18 text:title];
toplabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:toplabel];
_topTitleLabel = toplabel;
[_topTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(self.mas_centerY);
make.centerX.equalTo(self.mas_centerX);
make.width.equalTo(self.mas_width).multipliedBy(0.6);
}];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
[btn setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
[self addSubview:btn];
_backBtn = btn;
[_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.mas_left).offset(5);
make.centerY.equalTo(_topTitleLabel.mas_centerY);
make.height.equalTo(@20);
make.width.equalTo(@50);
}];
if(rightText){
UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
btn2.titleLabel.font = Font16;
[btn2 setTitleColor:Color333333 forState:UIControlStateNormal];
[btn2 addTarget:self action:@selector(clickRight) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn2];
_rightBtn = btn2;
[_rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.mas_right).offset(-5);
make.centerY.equalTo(_topTitleLabel.mas_centerY);
make.height.equalTo(@20);
make.width.equalTo(@50);
}];
}
}
return self;
}
点击事件处理
-(void)clickRight{
if(self.clickRightBtnBlock)
self.clickRightBtnBlock();
}
-(void)clickBack{
if(self.gobackBlock)
self.gobackBlock();
}
属性样式设置
标题颜色
-(void)setTitleColor:(UIColor *)titleColor{
self.topTitleLabel.textColor =titleColor;
}
背景色
-(void)setViewColor:(UIColor *)viewColor{
self.backgroundColor = viewColor;
}
隐藏属性
-(void)setHidden:(BOOL)hidden{
self.hidden = hidden;
}
外界使用
创建时提供标题、右标题、左右按钮的代码block即可。
总结:比较简陋,只有基本的常用功能。请按需使用。