美文网首页
UIButton的自定义布局(如上下分布)

UIButton的自定义布局(如上下分布)

作者: sz流氓江 | 来源:发表于2016-12-25 08:36 被阅读48次

    系统UIButton控件的默认布局是左右分布的,有时候我们又会需要一些特殊的布局,我们一般采用设置 titleEdgeInsets 这类属性解决。其实上有更好的方法:

    首先创建一个类继承自UIButton,例如:

    
    @interface HMButton : UIButton
    
    @end
    
    

    然后在.m文件中 重写几个方法

    
    - (CGRect)backgroundRectForBounds:(CGRect)bounds;
    
    - (CGRect)contentRectForBounds:(CGRect)bounds;
    
    - (CGRect)titleRectForContentRect:(CGRect)contentRect;
    
    - (CGRect)imageRectForContentRect:(CGRect)contentRect;
    
    

    例如

    
    @implementation HMButton 
    
    - (CGRect)imageRectForContentRect:(CGRect)contentRect
    
    {
    
    CGFloat h = self.bounds.size.height * 0.3;
    
    CGFloat w = h;
    
    CGFloat x = (self.bounds.size.width - w) * 0.5;
    
    CGFloat y = self.bounds.size.height * 0.3;
    
    return CGRectMake(x, y, w, h);
    
    }
    
    - (CGRect)titleRectForContentRect:(CGRect)contentRect
    
    {
    
    return CGRectMake(0, self.bounds.size.height * 0.6, self.bounds.size.width, self.bounds.size.height * 0.3);
    
    }
    
    @end
    
    

    效果如下

    相关文章

      网友评论

          本文标题:UIButton的自定义布局(如上下分布)

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