主要是两个方法:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
//初始化属性
[self initProperty];
//创建组件
[self createComponent];
}
return self;
}
- (void)initProperty
{
self.backgroundColor = UIColorFromRGB_hex(0xf2a2b2f);
}
- (void)createComponent
{
_leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
_leftButton.backgroundColor = [UIColor clearColor];
_rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
_rightButton.backgroundColor = [UIColor clearColor];
_leftLabel = [[UILabel alloc] init];
_leftLabel.backgroundColor = [UIColor clearColor];
_leftLabel.textColor = UIColorFromRGB_hex(0xf4f4f4);
_leftLabel.font = [UIFont boldSystemFontOfSize:18.f];
_leftLabel.textAlignment = NSTextAlignmentLeft;
_titleLabel = [[UILabel alloc] init];
_titleLabel.backgroundColor = [UIColor clearColor];
_titleLabel.textColor = UIColorFromRGB_hex(0xf4f4f4);
_titleLabel.font = [UIFont boldSystemFontOfSize:20.f];
_titleLabel.textAlignment = NSTextAlignmentCenter;
_bgImageView = [[UIImageView alloc] init];
[self addSubview:_leftButton];
[self addSubview:_rightButton];
[self addSubview:_leftLabel];
[self addSubview:_titleLabel];
[self addSubview:_bgImageView];
}
初始化做的事情只是创建一些组件,而不去设置尺寸,所有组件的尺寸放在下面这个方法中去做:
- (void)layoutSubviews
{
float offset = 0.f;
if (self.bounds.size.height>44) {
offset = 8.f;
}
_leftButton.frame = CGRectMake(0, offset+(self.bounds.size.height-30)/2, 90, 40);
_leftLabel.frame = CGRectMake(_leftButton.frame.origin.x+_leftButton.frame.size.width+8, offset+(self.bounds.size.height-20)/2, 45, 20);
_titleLabel.frame = CGRectMake(0, offset+(self.bounds.size.height-30)/2, self.bounds.size.width, 30);
_rightButton.frame = CGRectMake(self.bounds.size.width-90, offset+(self.bounds.size.height-30)/2, 90, 40);
_bgImageView.frame = CGRectMake(0, self.frame.size.height-1, self.frame.size.width, 1);
}