美文网首页
UIButton按钮文字图片任意布局

UIButton按钮文字图片任意布局

作者: 江河_ios | 来源:发表于2018-01-18 16:02 被阅读0次

实现方法

重写下面两个方法,返回正确的布局即可。

- (CGRect)titleRectForContentRect:(CGRect)contentRect;

- (CGRect)imageRectForContentRect:(CGRect)contentRect;

// 自定义代码

#import@interface YHCoustomButton : UIButton

@property (nonatomic,assign) CGRect titleRect;

@property (nonatomic,assign) CGRect imageRect;

@end

#import "YHCoustomButton.h"

@implementation YHCoustomButton

- (CGRect)titleRectForContentRect:(CGRect)contentRect{

    if (!CGRectIsEmpty(self.titleRect) && !CGRectEqualToRect(self.titleRect, CGRectZero)) {

        return self.titleRect;

    }

    return [super titleRectForContentRect:contentRect];

}

- (CGRect)imageRectForContentRect:(CGRect)contentRect{

    if (!CGRectIsEmpty(self.imageRect) && !CGRectEqualToRect(self.imageRect, CGRectZero)) {

        return self.imageRect;

    }

    return [super imageRectForContentRect:contentRect];

}

//实现

-(YHCoustomButton *)garyButton

{

    if (!_garyButton) {

        _garyButton=[YHCoustomButton buttonWithType:UIButtonTypeCustom];

        _garyButton.backgroundColor=YHGrayColor(238);

        _garyButton.layer.masksToBounds=YES;

        _garyButton.layer.cornerRadius=5;

        [_garyButton setImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];

        [_garyButton setAdjustsImageSizeForAccessibilityContentSizeCategory:YES];

        [_garyButton setTitle:@"搜索" forState:UIControlStateNormal];

        [_garyButton setTitleColor:YHGrayColor(170) forState:UIControlStateNormal];

        _garyButton.titleLabel.font=YHFont(42);

        CGFloat TOP=(YHPoint(110)-YHPoint(45))/2;

        _garyButton.imageRect=CGRectMake(YHPoint(500), TOP, YHPoint(45), YHPoint(45));

        _garyButton.titleRect=CGRectMake(YHPoint(500)+YHPoint(60), TOP, YHPoint(110), YHPoint(45));

    }

    return _garyButton;

}

效果视图

相关文章

网友评论

      本文标题:UIButton按钮文字图片任意布局

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