iOS-自定义 UIButton-文字在左、图片在右(一)

自定义 HQCustomButton 继承自 UIButton,重写layoutSubviews方法(见如下代码):

 
#import "HQCustomButton.h"

@implementation HQCustomButton
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    /** 修改 title 的 frame */
    // 1.获取 titleLabel 的 frame
    CGRect titleLabelFrame = self.titleLabel.frame;
    // 2.修改 titleLabel 的 frame
    
    
    titleLabelFrame.origin.x = (self.frame.size.width-self.titleLabel.frame.size.width-self.imageView.frame.size.width)/2;
    // 3.重新赋值
    self.titleLabel.frame = titleLabelFrame;
    
    /** 修改 imageView 的 frame */
    // 1.获取 imageView 的 frame
    CGRect imageViewFrame = self.imageView.frame;
    // 2.修改 imageView 的 frame
    imageViewFrame.origin.x = CGRectGetMaxX(self.titleLabel.frame);
    // 3.重新赋值
    self.imageView.frame = imageViewFrame;
}
@end

然后改变图片大小 放上去 扩展image方法

.h 文件


#import 

@interface UIImage (ALinExtension)
/**
 *  改变图片大小
 *
 *  @param image      原始图片
 *  @param targetSize 需要返回图片大小
 *
 *  @return 返回图片
 */
+ (UIImage *)image:(UIImage*)image byScalingToSize:(CGSize)targetSize;


@end

.m文件

#import "UIImage+ALinExtension.h"
#import 
@implementation UIImage (ALinExtension)

+ (UIImage *)image:(UIImage*)image byScalingToSize:(CGSize)targetSize {
    UIImage *sourceImage = image;
    UIImage *newImage = nil;
    
    UIGraphicsBeginImageContext(targetSize);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = CGPointZero;
    thumbnailRect.size.width  = targetSize.width;
    thumbnailRect.size.height = targetSize.height;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage ;
}

@end

你可能感兴趣的:(iOS-自定义 UIButton-文字在左、图片在右(一))