自定义水平和竖直按钮

作者: 蒋昉霖 | 来源:发表于2016-03-17 18:12 被阅读311次

    这两天都没怎么学习..好吧,罪过罪过...
    今天放连个自定义的Button吧.很简单的东西...高手勿喷
    我们开发中这种需求很常见,如图所示

    Snip20160317_1.png
    Snip20160317_2.png

    这种自定义样式的button,如果产品没有要求,我们可以在一个view上放一个button一个label来实现,但是这样的话点击label是无效的,虽然可以通过我们上次写的hitText和pointInside方法来实现,但是这样就麻烦很多,

    我们都知道,Button本身自带的就有一个Label和一个ImageView控件,我们何不通过更改内部属性的frame来实现自定义控件呢

    话不多说,直接上代码了

    JXHHorizontalButton 水平方向的自定义按钮

    - (instancetype)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
            [self p_setupView];
        }
        return self;
    }
    // 内部只实现一次的样式统一写在一个方法里面,方便用纯代码和,xib和sb创建的时候调用
    - (void)p_setupView
    {
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    }
    
    - (void)awakeFromNib
    {
        [self p_setupView];
    }
    
    // 更改frame在这个方法里写,当视图尺寸发生改变的时候调用
    - (void)layoutSubviews
    {
        [super layoutSubviews];
        
        // 原理很简单,右边的图片尺寸是定死的,但是左边label有多宽不定,所以根据图片大小来更改label尺寸,适配的话自己微调
        // 设置label
        self.titleLabel.x = 0;
        self.titleLabel.y = 0;
        // width = buttonwith - buttonHeigh;
        self.titleLabel.width = self.width - self.height;
        self.titleLabel.height = self.height;
        // 调整图片
        self.imageView.x = self.width - self.height;
        self.imageView.y = 0;
        self.imageView.width = self.height;
        self.imageView.height = self.height;
    }
    

    JXHVerticalButton竖直方向的按钮布局

    代码基本一样,就不多做解释了,哦也,就这些了

    - (void)p_setup
    {
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    
    - (instancetype)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
            [self p_setup];
        }
        return self;
    }
    
    - (void)awakeFromNib
    {
        [self p_setup];
    }
    
    - (void)layoutSubviews
    {
        [super layoutSubviews];
        
        // 调整图片
        self.imageView.x = 0;
        self.imageView.y = 0;
        self.imageView.width = self.width;
        self.imageView.height = self.imageView.width;
        
        // 调整文字
        self.titleLabel.x = 0;
        self.titleLabel.y = self.imageView.height;
        self.titleLabel.width = self.width;
        self.titleLabel.height = self.height - self.titleLabel.y;
        XHLog(@"%zd",self.imageView.height);
        XHLog(@"---%zd",self.titleLabel.y);
    }
    

    相关文章

      网友评论

      本文标题:自定义水平和竖直按钮

      本文链接:https://www.haomeiwen.com/subject/zlyclttx.html