美文网首页
自定义Button上image、title位置

自定义Button上image、title位置

作者: MinimalismC | 来源:发表于2018-07-11 22:11 被阅读0次

在实际开发中,系统默认的UIButton不能满足需求,需要对button进行自定义。

UIButton的默认布局是: title在右, image在左。

image

如果要实现title在左,image在右,或者title、image在上/下,或者其他位置,就需要自定义button.

image

通常我们调整位置image和title的位置有两种方式:
1、直接调整EdgeInsets

@property (nonatomic) UIEdgeInsets titleEdgeInsets;
@property (nonatomic) UIEdgeInsets imageEdgeInsets;     

EdgeInsets是结构体,上左下右去添加约束,这里不重点讲。

2、自定义Button继承自UIButton, 重写如下方法:

- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;

这里看看image、title在水平方向效果,竖直方向的可以自己试试,下面有对应的枚举标识。

image image

代码如下:

typedef NS_ENUM(NSInteger, KBMainButtonStyle) {
    
    ImageLeftTitleRight = 0,    //图片左title右
    ImageRightTitleLeft,        //图片右title左
    ImageTopTitleDown,          //图片上title下
    ImageDownTitleTop           //图片下title上
};

- (void)setButonStyle:(KBMainButtonStyle)buttonStyle imgFrame:(CGRect)imgFrame {
    
    _buttonStyle = buttonStyle;
    _imgFrame = imgFrame;
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect  {

    CGFloat originX = 0;
    CGFloat originY = 0;
    CGFloat width   = 0;
    CGFloat height  = 0;
    CGRect rec = CGRectZero;
    
    switch (_buttonStyle)  {
        case ImageLeftTitleRight:
        {
            originX = _imgFrame.origin.x + _imgFrame.size.width;
            originY = 0;
            width   = contentRect.size.width - originX;
            height  = contentRect.size.height;
            rec     = CGRectMake(originX, originY, width, height);
        }
            break;
        case ImageRightTitleLeft:
        {
            originX = 0;
            originY = 0;
            width   = contentRect.size.width - _imgFrame.size.width;
            height  = contentRect.size.height;
            rec     = CGRectMake(originX, originY, width, height);
        }
            break;
        case ImageTopTitleDown:
        {
            originX = 0;
            originY =  _imgFrame.origin.y + _imgFrame.size.height;
            width   = contentRect.size.width;
            height  = contentRect.size.height - originY;
            rec     = CGRectMake(originX, originY, width, height);
        }
            break;
        case ImageDownTitleTop:
        {
            originX = 0;
            originY = 0;
            width   = contentRect.size.width;
            height  = contentRect.size.height - _imgFrame.size.height;
            rec     = CGRectMake(originX, originY, width, height);
        }
            break;
        default:
            break;
    }
    return rec;
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    
    return _imgFrame;
}

详细代码,见Demo

相关文章

网友评论

      本文标题:自定义Button上image、title位置

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