UIButton按钮文字图片任意布局

实现方法

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

- (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;

}


效果视图
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容