如何实现按钮的图片在右边,文字在左边

简介: 如何实现按钮的图片在右边,文字在左边

按钮设置了文字和图片,若宽度足够展开的话,默认都是图片在作,文字在右。想文字在左,图片在右有三种方法。

第一种方法很简单。通过设置setSemanticContentAttribute属性来实现。

       _bgBtn2 = [[UIButton alloc] init];
        [_bgBtn2 setBackgroundColor:[UIColor clearColor]];
        [_bgBtn2 setTitle:@"关注问题(243)" forState:UIControlStateNormal];
        [_bgBtn2.titleLabel setFont:[UIFont systemFontOfSize:12]];
        [_bgBtn2 setTitleColor:DYHighlightColor forState:UIControlStateNormal];
        [_bgBtn2 setImage:[UIImage imageNamed:@"icon_quest31"] forState:UIControlStateNormal];
**[_bgBtn2 setSemanticContentAttribute:UISemanticContentAttributeForceRightToLeft];**

第二种方法是通过设置titleEdgeInsets和setImageEdgeInsets来实现。

        _selectBtn = [[BGSwapButton alloc] initWithTitle:@"排序" titleColor:DEFAULT_TITLE_LIGHT_FRONT_COLOR selectedTitleColor:DYHighlightColor icon:[UIImage imageNamed:@"icon_quest32"] selectedIcon:[UIImage imageNamed:@"icon_quest_sort"] frame:CGRectMake(FULL_WIDTH-40-COMMON_EDGE_DISTANCE, 12+100+12+28+12+8+(45-12.0)/2, 40, 12)];
        _selectBtn.titleLabel.font = BGFont(12);
        **_selectBtn.titleEdgeInsets=UIEdgeInsetsMake(0, -(40 -9)+8,0, 0);//上左下右
        [_selectBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 40-9, 0, 0)];//上左下右**

第三种方法是通过一个按钮分类,设置方法来实现,使用也很简单。

            UIButton *btn = [UIButton buttonWithTitle:@"收藏" font:SystemFontOfSize(13) color:TextBlackColor];
            [btn setTitle:@"已收藏" forState:UIControlStateSelected];
            [btn setTitleColor:MainAPPColor forState:UIControlStateSelected];
            [btn setImage:[UIImage imageNamed:@"icon_collect_no"] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:@"icon_collect_yes"] forState:UIControlStateSelected];
            [btn addTarget:self action:@selector(collectAction:) forControlEvents:UIControlEventTouchUpInside];
            [btn layoutButtonWithEdgeInsetsStyle:JKButtonEdgeInsetsStyleRight imageTitleSpace:5];

UIButton+Commemt.h文件:

#import <UIKit/UIKit.h>

// 定义一个枚举(包含了四种类型的button)
typedef NS_ENUM(NSUInteger, JKButtonEdgeInsetsStyle) {
    JKButtonEdgeInsetsStyleTop, // image在上,label在下
    JKButtonEdgeInsetsStyleLeft, // image在左,label在右
    JKButtonEdgeInsetsStyleBottom, // image在下,label在上
    JKButtonEdgeInsetsStyleRight // image在右,label在左
};


NS_ASSUME_NONNULL_BEGIN

@interface UIButton (Commemt)

/// 标题
@property (nonatomic,copy)NSString *jk_title;
/// 选中的标题
@property (nonatomic,copy)NSString *jk_selectedTitle;
/// 标题颜色
@property (nonatomic,strong)UIColor *jk_titleColor;
/// 选中的标题颜色
@property (nonatomic,strong)UIColor *jk_selectedTitleColor;

//
@property (nonatomic,strong)UIColor *jk_HighlightedTitleColor;

//普通的背景图片
@property (nonatomic,strong)UIImage *jk_normalImage;
//选中的背景图片
@property (nonatomic,strong)UIImage *jk_selectedImage;
//增加点击的区域
@property(nonatomic, assign) UIEdgeInsets jk_hitTestEdgeInsets;

//设置背景颜色
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state;
//按钮的的样式和间隔
/**
 *  设置button的titleLabel和imageView的布局样式,及间距
 *
 *  @param style titleLabel和imageView的布局样式
 *  @param space titleLabel和imageView的间距
 */
- (void)layoutButtonWithEdgeInsetsStyle:(JKButtonEdgeInsetsStyle)style
                        imageTitleSpace:(CGFloat)space;


@end

NS_ASSUME_NONNULL_END

UIButton+Commemt.m文件:


#import "UIButton+Commemt.h"
#import "objc/runtime.h"

@implementation UIButton (Commemt)

@dynamic jk_hitTestEdgeInsets;
static const NSString *KEY_HIT_TEST_EDGE_INSETS =  @"HitTestEdgeInsets";

- (void)setJk_hitTestEdgeInsets:(UIEdgeInsets)jk_hitTestEdgeInsets {
    NSValue *value = [NSValue value:&jk_hitTestEdgeInsets withObjCType:@encode(UIEdgeInsets)];
    objc_setAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


- (UIEdgeInsets)jk_hitTestEdgeInsets {
    NSValue *value = objc_getAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS);
    if(value) {
        UIEdgeInsets edgeInsets;
        [value getValue:&edgeInsets];
        return edgeInsets;
    }else {
        return UIEdgeInsetsZero;
    }
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if(UIEdgeInsetsEqualToEdgeInsets(self.jk_hitTestEdgeInsets, UIEdgeInsetsZero) ||       !self.enabled || self.hidden) {
        return [super pointInside:point withEvent:event];
}
    CGRect relativeFrame = self.bounds;
    CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.jk_hitTestEdgeInsets);
    return CGRectContainsPoint(hitFrame, point);
}

//image

- (void)setJk_normalImage:(UIImage *)jk_normalImage {
    objc_setAssociatedObject(self, @selector(jk_normalImage), jk_normalImage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setImage:jk_normalImage forState:UIControlStateNormal];
}

- (UIImage *)jk_normalImage {
    return objc_getAssociatedObject(self, @selector(jk_normalImage));
}

- (void)setJk_selectedImage:(UIImage *)jk_selectedImage {
    objc_setAssociatedObject(self, @selector(jk_selectedImage), jk_selectedImage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setImage:jk_selectedImage forState:UIControlStateSelected];
}

- (UIImage *)jk_selectedImage {
    return objc_getAssociatedObject(self, @selector(jk_selectedImage));
}

/

- (void)setJk_title:(NSString *)jk_title {
    objc_setAssociatedObject(self, @selector(jk_title), jk_title, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self setTitle:jk_title forState:UIControlStateNormal];
}

- (NSString *)jk_title {
    return objc_getAssociatedObject(self, @selector(jk_title));
}

//
- (void)setJk_selectedTitle:(NSString *)jk_selectedTitle {
    objc_setAssociatedObject(self, @selector(jk_selectedTitle), jk_selectedTitle, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self setTitle:jk_selectedTitle forState:UIControlStateSelected];
}

- (NSString *)jk_selectedTitle {
    return objc_getAssociatedObject(self, @selector(jk_selectedTitle));
}

//

- (UIColor *)jk_titleColor {
    return objc_getAssociatedObject(self, @selector(jk_titleColor));
}

- (void)setJk_titleColor:(UIColor *)jk_titleColor {
    objc_setAssociatedObject(self, @selector(jk_titleColor), jk_titleColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setTitleColor:jk_titleColor forState:UIControlStateNormal];
}

- (UIColor *)jk_selectedTitleColor {
    return objc_getAssociatedObject(self, @selector(jk_selectedTitleColor));
}

- (void)setJk_selectedTitleColor:(UIColor *)jk_selectedTitleColor {
    objc_setAssociatedObject(self, @selector(jk_selectedTitleColor), jk_selectedTitleColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setTitleColor:jk_selectedTitleColor forState:UIControlStateSelected];
}

///
- (void)setJk_HighlightedTitleColor:(UIColor *)jk_HighlightedTitleColor {
    objc_setAssociatedObject(self, @selector(jk_HighlightedTitleColor), jk_HighlightedTitleColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setTitleColor:jk_HighlightedTitleColor forState:UIControlStateHighlighted];
}

- (UIColor *)jk_HighlightedTitleColor {
    return objc_getAssociatedObject(self, @selector(jk_HighlightedTitleColor));
}

//
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
    [self setBackgroundImage:[UIButton imageWithColor:backgroundColor] forState:state];
}

+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

//按钮样式

- (void)layoutButtonWithEdgeInsetsStyle:(JKButtonEdgeInsetsStyle)style imageTitleSpace:(CGFloat)space {
    // 1. 得到imageView和titleLabel的宽、高
    CGFloat imageWith = self.imageView.intrinsicContentSize.width;
    if((imageWith != ((NSInteger)imageWith)) && (((NSInteger)(imageWith+0.5)) != ((NSInteger)(imageWith))))
    {
        imageWith = imageWith + 0.5;
    }
    CGFloat imageHeight = self.imageView.intrinsicContentSize.height;

    CGFloat labelWidth = self.titleLabel.intrinsicContentSize.width;
    if((labelWidth != ((NSInteger)labelWidth)) && (((NSInteger)(labelWidth+0.5)) != ((NSInteger)(labelWidth))))
    {
        labelWidth = labelWidth + 0.5;
    }
    CGFloat labelHeight = self.titleLabel.intrinsicContentSize.height;

    // 2. 声明全局的imageEdgeInsets和labelEdgeInsets
    UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero;
    UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero;

    // 上左下右
    switch (style) {
        case JKButtonEdgeInsetsStyleTop: {
            imageEdgeInsets = UIEdgeInsetsMake(-labelHeight - space / 2.0, 0, 0, -labelWidth);
            labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith, -imageHeight - space / 2.0, 0);
        }
        break;
        case JKButtonEdgeInsetsStyleLeft: {
            imageEdgeInsets = UIEdgeInsetsMake(0, -space / 2.0, 0, space / 2.0);
            labelEdgeInsets = UIEdgeInsetsMake(0, space / 2.0, 0, -space / 2.0);
        }
        break;
        case JKButtonEdgeInsetsStyleRight: {
            imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth + space / 2.0, 0, -labelWidth - space / 2.0);
            labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith - space / 2.0, 0, imageWith + space / 2.0);
        }
        break;
        case JKButtonEdgeInsetsStyleBottom: {
            imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight - space / 2.0, -labelWidth);
            labelEdgeInsets = UIEdgeInsetsMake(-imageHeight - space / 2.0, -imageWith, 0, 0);
        }
        break;

        default:
            break;
    }

    // 4. 赋值
    self.titleEdgeInsets = labelEdgeInsets;
    self.imageEdgeInsets = imageEdgeInsets;
}

@end

但是这些方法能解决99%的手机图文按钮适配,但是我遇到一个特定的手机(iOS13.6.1 XR手就),以上第一种方法和第三种方法都解决不了,第二种方法没有尝试(由于这需要计算按钮的边距通用性很差)。所以不考虑那个特殊手机的情况,建议采用第一种方法和第三种方法。若遇到测试用这个特定手机只能使用《iOS13.6.1系统XR手机图文按钮显示不全问题》。

目录
相关文章
|
6月前
VSCode如何自动换行,右侧换行间距长度,隐藏右侧代码预览(Minimap代码缩略图滚动条),比对代码差异窗口也自动换行
VSCode如何自动换行,右侧换行间距长度,隐藏右侧代码预览(Minimap代码缩略图滚动条),比对代码差异窗口也自动换行
|
4月前
动态黑窗口打印文字404页面源码
动态黑窗口打印文字404页面源码
28 2
|
4月前
|
JavaScript
Elementplus淡入淡出效果,头部顶栏如何设置文字隐藏效果,默认图标如何收缩,icons如何通过类进行替换,侧边栏如何添加阴影,右边如何设置高度,侧边栏如何设置阴影,如何让icon与文字
Elementplus淡入淡出效果,头部顶栏如何设置文字隐藏效果,默认图标如何收缩,icons如何通过类进行替换,侧边栏如何添加阴影,右边如何设置高度,侧边栏如何设置阴影,如何让icon与文字
vitepress如何配置右上角的小两侧标志,利用nav标签进行修改,右侧边栏如何设置成自动弹出水平框,让原先隐藏的框能够显示出来
vitepress如何配置右上角的小两侧标志,利用nav标签进行修改,右侧边栏如何设置成自动弹出水平框,让原先隐藏的框能够显示出来
输入框贴贴去除样式并插入到指定光标位置(contenteditable=“true“ 实现的输入框也支持)
输入框贴贴去除样式并插入到指定光标位置(contenteditable=“true“ 实现的输入框也支持)
105 0
|
6月前
如何在屏幕的任意位置拖拽控制图片的移动?
如何在屏幕的任意位置拖拽控制图片的移动?
115 1
|
6月前
|
iOS开发
ios中,输入框获得焦点时,页面输入框被遮盖,定位的元素位置错乱
ios中,输入框获得焦点时,页面输入框被遮盖,定位的元素位置错乱
83 1
|
6月前
|
前端开发 JavaScript
uniapp四个元素点击那个哪个变色,其他的还变原来的颜色
uniapp四个元素点击那个哪个变色,其他的还变原来的颜色
388 0
|
6月前
指定文字浮动区域,动起来的效果棒极了
指定文字浮动区域,动起来的效果棒极了
82 0
设置按钮背景为透明去掉button按钮左右两边的留白
设置按钮背景为透明去掉button按钮左右两边的留白