Objective-C UIButton 自定义图片位置

在项目中经常会遇到一个按钮上放一个图片 位置有可能会是在标题的上,下,左,右 如果一个按钮,可以单独设置titleEdgeInsets和imageEdgeInsets即可,但是如果有很多 类似的按钮但是设置就很麻烦。为了解决这个问题 我们写一个UIButton的Category

#import <UIKit/UIKit.h>

typedef NS_ENUM(NSUInteger,ButtonEdgeInsetsStyle) {
    ButtonEdgeInsetsStyleTop,
    ButtonEdgeInsetsStyleLeft,
    ButtonEdgeInsetsStyleRight,
    ButtonEdgeInsetsStyleBottom,
};

@interface UIButton (EdgeInsets)

/**非选中图片*/
@property (copy, nonatomic) NSString *normalImageName;
/**选中图片*/
@property (copy, nonatomic) NSString *selectedImageName;
/**默认图片*/
@property (copy, nonatomic) NSString *defaultImageName;

- (void)setImagePositionWithEdgeInsetsStyle:(ButtonEdgeInsetsStyle)style imageSpace:(CGFloat)space;

- (void)setDefaultImageWithNamed:(NSString *)imgName;

@end

为什么要设置三个图片属性,为了解决这样的需求,比如有很多筛选按钮,产品经理说没有排序用一张图片,升序用一张图片,降序用一张图片。

#import "UIButton+EdgeInsets.h"
#import <objc/runtime.h>

@implementation UIButton (EdgeInsets)

- (void)setImagePositionWithEdgeInsetsStyle:(ButtonEdgeInsetsStyle)style imageSpace:(CGFloat)space
{
    
    // 得到imageView和titleLabel的宽、高
    CGFloat imageWith = self.currentImage.size.width;
    CGFloat imageHeight = self.currentImage.size.height;
    
    // 获取TitleSize
    CGSize titleSize = [self sizeForText:[self titleForState:UIControlStateNormal] font:self.titleLabel.font size:CGSizeMake(HUGE, HUGE) mode:self.titleLabel.lineBreakMode];
    
    CGFloat labelWidth = titleSize.width;
    CGFloat labelHeight = titleSize.height;
   
    // 声明全局的imageEdgeInsets和labelEdgeInsets
    UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero;
    UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero;
    
    // 根据style和space得到imageEdgeInsets和labelEdgeInsets的值
    switch (style) {
        case ButtonEdgeInsetsStyleTop: {
            imageEdgeInsets = UIEdgeInsetsMake(-labelHeight-space, 0, 0, -labelWidth);
            labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith, -imageHeight-space, 0);
        }
            break;
        case ButtonEdgeInsetsStyleLeft: {
            imageEdgeInsets = UIEdgeInsetsMake(0, -space, 0, space);
            labelEdgeInsets = UIEdgeInsetsMake(0, space, 0, -space);
        }
            break;
        case ButtonEdgeInsetsStyleBottom: {
            imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight-space, -labelWidth);
            labelEdgeInsets = UIEdgeInsetsMake(-imageHeight-space, -imageWith, 0, 0);
        }
            break;
        case ButtonEdgeInsetsStyleRight: {
            imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth+space, 0, -labelWidth-space);
            labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith-space, 0, imageWith+space);
        }
            break;
        default:
            break;
    }
    // 赋值
    self.titleEdgeInsets = labelEdgeInsets;
    self.imageEdgeInsets = imageEdgeInsets;
}

- (void)setSelected:(BOOL)selected
{
    if (selected) {
        [self setImage:[UIImage imageNamed:self.selectedImageName] forState:UIControlStateNormal];
    }
    else{
         [self setImage:[UIImage imageNamed:self.normalImageName] forState:UIControlStateNormal];
    }
}

- (void)setDefaultImageWithNamed:(NSString *)imgName
{
    [self setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
    self.defaultImageName = imgName;
}

#pragma mark - pravite Method
static const void *normalImageNameKey = &normalImageNameKey;
- (void)setNormalImageName:(NSString *)normalImageName
{
    objc_setAssociatedObject(self, normalImageNameKey, normalImageName,  OBJC_ASSOCIATION_COPY);
}
- (NSString *)normalImageName
{
    return objc_getAssociatedObject(self, normalImageNameKey);
}

static const void *selectedImageNameKey = &selectedImageNameKey;
- (void)setSelectedImageName:(NSString *)selectedImageName
{
    objc_setAssociatedObject(self, selectedImageNameKey, selectedImageName,  OBJC_ASSOCIATION_COPY);
}
- (NSString *)selectedImageName
{
    return objc_getAssociatedObject(self, selectedImageNameKey);
}

static const void *defaultImageNameKey = &defaultImageNameKey;
- (void)setDefaultImageName:(NSString *)defaultImageName
{
    objc_setAssociatedObject(self, defaultImageNameKey, defaultImageName,  OBJC_ASSOCIATION_COPY);
}
- (NSString *)defaultImageName
{
    return objc_getAssociatedObject(self, defaultImageNameKey);
}


#pragma mark - Drawing
- (CGSize)sizeForText:(NSString *)text font:(UIFont *)font size:(CGSize)size mode:(NSLineBreakMode)lineBreakMode {
    CGSize result;
    if (!font) font = [UIFont systemFontOfSize:12];
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        NSMutableDictionary *attr = [NSMutableDictionary new];
        attr[NSFontAttributeName] = font;
        if (lineBreakMode != NSLineBreakByWordWrapping) {
            NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
            paragraphStyle.lineBreakMode = lineBreakMode;
            attr[NSParagraphStyleAttributeName] = paragraphStyle;
        }
        CGRect rect = [text boundingRectWithSize:size
                                         options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                      attributes:attr context:nil];
        result = rect.size;
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        result = [text sizeWithFont:font constrainedToSize:size lineBreakMode:lineBreakMode];
#pragma clang diagnostic pop
    }
    return result;
}

调用

#import "ViewController.h"
#import "UIButton+EdgeInsets.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIButton *buttonTop;
@property (weak, nonatomic) IBOutlet UIButton *buttonBottom;
@property (weak, nonatomic) IBOutlet UIButton *buttonLeft;
@property (weak, nonatomic) IBOutlet UIButton *buttonRight;

@property (weak, nonatomic) IBOutlet UIButton *button4;
@property (weak, nonatomic) IBOutlet UIButton *button5;
@property (weak, nonatomic) IBOutlet UIButton *button6;

@property (assign, nonatomic) BOOL isSelected;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self.buttonTop setDefaultImageWithNamed:@"sort_filter_default_img"];
    [self.buttonTop setImagePositionWithEdgeInsetsStyle:ButtonEdgeInsetsStyleTop imageSpace:0];

    [self.buttonBottom setDefaultImageWithNamed:@"sort_filter_default_img"];
    [self.buttonBottom setImagePositionWithEdgeInsetsStyle:ButtonEdgeInsetsStyleBottom imageSpace:0];
    
    [self.buttonLeft setDefaultImageWithNamed:@"sort_filter_default_img"];
    [self.buttonLeft setImagePositionWithEdgeInsetsStyle:ButtonEdgeInsetsStyleLeft imageSpace:5];
    
    [self.buttonRight setDefaultImageWithNamed:@"sort_filter_default_img"];
    [self.buttonRight setImagePositionWithEdgeInsetsStyle:ButtonEdgeInsetsStyleRight imageSpace:5];
    
    [self.button4 setDefaultImageWithNamed:@"sort_filter_asc_img"];
    [self.button4 setSelectedImageName:@"sort_filter_asc_img"];
    [self.button4 setNormalImageName:@"sort_filter_desc_img"];
    [self.button4 setImagePositionWithEdgeInsetsStyle:ButtonEdgeInsetsStyleRight imageSpace:0];
    self.isSelected = YES;
    
    [self.button5 setDefaultImageWithNamed:@"sort_filter_default_img"];
    [self.button5 setImagePositionWithEdgeInsetsStyle:ButtonEdgeInsetsStyleRight imageSpace:0];
    
    [self.button6 setDefaultImageWithNamed:@"sort_filter_default_img"];
    [self.button6 setImagePositionWithEdgeInsetsStyle:ButtonEdgeInsetsStyleRight imageSpace:0];
}

- (IBAction)btn4Action:(UIButton *)sender {
    
    self.isSelected = !self.isSelected;
    sender.selected = self.isSelected;
}

效果

Simulator Screen Shot - iPhone 5s - 2018-05-31 at 11.28.51.png

有需要的同学可以看看 git地址:https://github.com/destinyzhao/ButtonEdgeInsets

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Alice

效果类似于label从下往上滑(采用uiTableView实现)

首先附上效果图 ? ? 进行描述一下:效果就是类似于是一个竖直方向的滚动视图 并且方向是从下往上  并且能够一直这样循环下去。 代码“ // // ViewC...

2325
来自专栏TechBox

史上最全的iOS之UITextView实现placeHolder占位文字的N种方法前言方法一方法二方法三方法四方法五

2183
来自专栏coding...

iOS开发-RAC+MVVM练手项目 图床App写在前面准备工作界面设计首页历史关于后记

前段时间闲着无聊和盆友就搞了个图床站Chevereto-Free,忽然发现居然有API提供,而且很简单,只需要一个KEY就可以

1162
来自专栏刘晓杰

RN实现头部NavBar

4087
来自专栏谈补锅

Quartz2D复习(四) --- 图层CALayer和动画CAAnimation

1)、在ios中,能看得见摸得着的东西基本上都是UIView, 比如按钮、文本标签、文本输入框、图标等,这些都是UIView

973
来自专栏Python疯子

Swift -标签页控制器(UITabBarController)用法

Simulator Screen Shot 2016年11月8日 19.11.36.png

5892
来自专栏iOS 开发

根据后台返回的UIButton title动态改变UIButton宽度

2204
来自专栏hrscy

iOS百度地图开发之路径规划

3913
来自专栏编程语言

iOS:宏定义(项目初期配置)(一)

1762
来自专栏ios 技术积累

ios 扩大UIButton点击范围

先了解Hit-Test请看上一篇文章 https://www.jianshu.com/writer#/notebooks/4989829/notes/3314...

2882

扫码关注云+社区

领取腾讯云代金券