实现方法
重写下面两个方法,返回正确的布局即可。
- (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;
}
![](https://img.haomeiwen.com/i3833191/bbe23aebcb625405.png)
网友评论