iOS-任意改变Button里面图片和文字的位置-Runtime使用

给Button分类添加属性、改变Button内图片和文字的位置

#import 
@interface UIButton (LayoutSubviews)
@property (assign, nonatomic) CGRect imageViewFrame;
@property (assign, nonatomic) CGRect titleLabelFrame;
@end

#import "UIButton+LPLayoutSubviews.h"
#import 
@implementation UIButton (LayoutSubviews)
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    [self swizzleMethod:@selector(layoutSubviews) swizzledSelector:@selector(aop_layoutSubviews)];
});
}

#pragma mark- 动态的替换两个方法
+ (void)swizzleMethod:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector{
Method originalMethod = class_getInstanceMethod([self class], originalSelector);
Method swizzledMethod = class_getInstanceMethod([self class], swizzledSelector);
if (class_addMethod([self class],originalSelector,method_getImplementation(swizzledMethod),method_getTypeEncoding(swizzledMethod))) {
    class_replaceMethod([self class],swizzledSelector,method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod));
} else {
    method_exchangeImplementations(originalMethod, swizzledMethod);
}
}

#pragma mark- 动态的添加属性
- (CGRect)imageViewFrame{
return [objc_getAssociatedObject(self, @selector(imageViewFrame)) CGRectValue];
}
- (void)setImageViewFrame:(CGRect)imageViewFrame{
objc_setAssociatedObject(self, @selector(imageViewFrame), [NSValue valueWithCGRect:imageViewFrame], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (CGRect)titleLabelFrame{
return [objc_getAssociatedObject(self, @selector(titleLabelFrame)) CGRectValue];
}
- (void)setTitleLabelFrame:(CGRect)titleLabelFrame{
objc_setAssociatedObject(self, @selector(titleLabelFrame), [NSValue valueWithCGRect:titleLabelFrame], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

#pragma mark- 替换layoutSubviews的方法
- (void)aop_layoutSubviews{
[self aop_layoutSubviews];
[CATransaction begin];
[CATransaction setDisableActions:YES];

if (!CGRectEqualToRect(self.imageViewFrame, CGRectZero)) {
    if (!CGRectEqualToRect(self.imageView.frame, self.imageViewFrame)) {
        self.imageView.frame = self.imageViewFrame;
    }
}

if (!CGRectEqualToRect(self.titleLabelFrame, CGRectZero)) {
    if (!CGRectEqualToRect(self.titleLabel.frame, self.titleLabelFrame)) {
        self.titleLabel.frame = self.titleLabelFrame;
    }
}

[CATransaction commit];
}
@end

使用:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"测试" forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"userPlaceIcon"] forState:UIControlStateNormal];
[self addSubview:button];

button.imageViewFrame = CGRectMake(0, 0, buttonW, buttonH*0.8);
button.titleLabelFrame = CGRectMake(0, buttonH*0.8, buttonW, buttonH*0.2);

效果展示

iOS-任意改变Button里面图片和文字的位置-Runtime使用_第1张图片
WechatIMG20481.jpeg

你可能感兴趣的:(iOS-任意改变Button里面图片和文字的位置-Runtime使用)