UIView的使用——如何自定义一个视图

来源:互联网 发布:三国正史武将排名 知乎 编辑:程序博客网 时间:2024/06/07 01:33

主要是两个方法:

- (id)initWithFrame:(CGRect)frame

{

   self = [superinitWithFrame:frame];

   if (self) {

        

       //初始化属性

        [selfinitProperty];

        

       //创建组件

        [selfcreateComponent];

        

    }

    return self;

}


- (void)initProperty

{

    self.backgroundColor =UIColorFromRGB_hex(0xf2a2b2f);

}


- (void)createComponent

{

    _leftButton = [UIButtonbuttonWithType:UIButtonTypeCustom];

    _leftButton.backgroundColor = [UIColorclearColor];

    

    _rightButton = [UIButtonbuttonWithType:UIButtonTypeCustom];

    _rightButton.backgroundColor = [UIColorclearColor];

    

   _leftLabel = [[UILabelalloc] init];

    _leftLabel.backgroundColor = [UIColorclearColor];

    _leftLabel.textColor =UIColorFromRGB_hex(0xf4f4f4);

    _leftLabel.font = [UIFontboldSystemFontOfSize:18.f];

    _leftLabel.textAlignment =NSTextAlignmentLeft;

    

   _titleLabel = [[UILabelalloc] init];

    _titleLabel.backgroundColor = [UIColorclearColor];

    _titleLabel.textColor =UIColorFromRGB_hex(0xf4f4f4);

    _titleLabel.font = [UIFontboldSystemFontOfSize:20.f];

    _titleLabel.textAlignment =NSTextAlignmentCenter;

    

   _bgImageView = [[UIImageViewalloc] init];

    

    [selfaddSubview:_leftButton];

    [selfaddSubview:_rightButton];

    [selfaddSubview:_leftLabel];

    [selfaddSubview:_titleLabel];

    [selfaddSubview:_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);

}




0 0
原创粉丝点击