自定义按钮 图片标题位置随意放置

栏目: IOS · 发布时间: 5年前

#图标和文字在一起是开发难免的问题,系统的按钮默认是图片居左的文字居右的,
且图片和文字的距离不好调整,图片的位置更是让人头疼,
故在闲暇之余封装了一个控件。
复制代码

所用到知识的

# 1、苹果系统自带的自动布局,减少第三方的依赖
# 2、kvo监听UIControl的状态
# 3、富文本的使用,如何更新约束,如何获取一段文字的宽高

复制代码

先看看效果

自定义按钮 图片标题位置随意放置

拥有功能

1、任意调整图片和文字的间距。
2、图片的位置可以放置在上下左右不同位置。
3、支持富文本,自定义布局,高亮和选中状态。
复制代码

如何使用

/**
 自定义按钮初始化方法

 @param image 默认的图片
 @param title 标题
 @param titleFond 标题大小
 @param imageMargin 标题与图标的距离
 @param imageAlignmentTYpe 图片的显示类型
 @return 自定义按钮的实例
 */
- (instancetype)initWithImage:(UIImage  *) image
                        title:(NSString *) title
                    titleFond:(UIFont *)   titleFond
                  imageMargin:(CGFloat)    imageMargin
           imageAlignmentTYpe:(MyButtonImageAlignmentTYpe )imageAlignmentTYpe;
   
   _myButton = [[MyButton alloc]initWithImage:[UIImage imageNamed:@"cache_pause"]
                                             title:@"来点我啊"
                                         titleFond:[UIFont systemFontOfSize:14]
                                       imageMargin:10
                                imageAlignmentTYpe:MyButtonImageAlignmentLeft];
                                
    [self.view addSubview:_myButton];
    self.myButton.frame = CGRectMake(20, 100, 120, 40);
    self.myButton.backgroundColor = UIColor.grayColor;
    [self.myButton setImage:[UIImage imageNamed:@"cache_delete"] withState:UIControlStateSelected];
    [self.myButton setImage:[UIImage imageNamed:@"cache_pause"] withState:UIControlStateHighlighted];
    [self.myButton setTitle:@"选中了" withState:UIControlStateSelected];
    [self.myButton setTitle:@"正在按下..." withState:UIControlStateHighlighted];
    [self.myButton setTitleColor:UIColor.blueColor withState:UIControlStateSelected];
    [self.myButton setTitleColor:UIColor.yellowColor withState:UIControlStateHighlighted];
  这样就可以了,和普通的按钮用法一样。
   
复制代码

关键代码

1、自定义布局(只列出了一种)
//图片居左
- (void)setImageLeftLayoutConstraint {
    CGFloat imageWidth  = self.normalImage.size.width;
    CGFloat titleWidth = [self sizeWithText:self.titleLabel.text font:self.titleLabel.font].width;
    CGFloat imageCenterXMargin = (imageWidth /2.0 - (imageWidth + titleWidth + self.imageMargin) / 2.0);
    //创建Image约束
    NSLayoutConstraint *imageCenterYLc = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    NSLayoutConstraint *imageCenterXLc = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:imageCenterXMargin];
    [self addConstraints:@[imageCenterYLc,imageCenterXLc]];
    //创建title约束
    NSLayoutConstraint *titleCenterYLc = [NSLayoutConstraint constraintWithItem:self.titleLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    NSLayoutConstraint *titleLeftLc = [NSLayoutConstraint constraintWithItem:self.titleLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.imageView attribute:NSLayoutAttributeRight multiplier:1.0 constant:self.imageMargin];
     [self addConstraints:@[titleCenterYLc,titleLeftLc]];
}

//获取文字的宽高
- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font {
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [text boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

//kvo监听
- (void)addObserver {
    [self addObserver:self
           forKeyPath:@"enabled"
              options: NSKeyValueObservingOptionNew
              context:nil];
    [self addObserver:self
           forKeyPath:@"selected"
              options: NSKeyValueObservingOptionNew
              context:nil];
    [self addObserver:self
           forKeyPath:@"highlighted"
              options: NSKeyValueObservingOptionNew
              context:nil];
    [self.titleLabel addObserver:self
                      forKeyPath:@"text"
                         options:NSKeyValueObservingOptionNew
                         context:nil];
}

//kvo 监听处理(只列出了部分)
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
   if ([keyPath isEqualToString:@"selected"]) {
        if(self.selected) {
            self.imageView.image           = self.selectedImage ? self.selectedImage : self.normalImage;
            self.backgroundColor           = self.selectedBackgroundColor  ? self.selectedBackgroundColor : self.normalBackgroundColor;
            if (!self.selectedTitleAttribute && !self.normalTitleAttribute) {
                self.titleLabel.text       = self.selectedTitle ? self.selectedTitle : self.normalTitle;
                self.titleLabel.textColor  = self.selectedTitleColor ? self.selectedTitleColor : self.normalTitleColor;
                return;
            }
            self.titleLabel.attributedText = self.selectedTitleAttribute ? self.selectedTitleAttribute : self.normalTitleAttribute;
        } else {
            self.imageView.image           = self.normalImage;
            self.backgroundColor           = self.normalBackgroundColor;
            if (!self.normalTitleAttribute) {
                self.titleLabel.text       = self.normalTitle;
                self.titleLabel.textColor  = self.normalTitleColor;
                return;
            }
            self.titleLabel.attributedText = self.normalTitleAttribute;
        }
    } 
    //监听到字体变化,更新自动布局
    if ([keyPath isEqualToString:@"text"]) {
        [self removeConstraints:self.constraints];
        [self.superview layoutIfNeeded];
        [self updateConstraints:self.imageAlignmentTYpe];
        [self.superview layoutIfNeeded];
    }
复制代码

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

乔布斯离开了,马斯克来了

乔布斯离开了,马斯克来了

[日]竹内一正 / 干太阳 / 中信出版社 / 2015-11

在电动汽车的创新上,特斯拉抓住了一个群体的独特需求,外形很酷,不烧油,智能化控制。所有的颠覆式创新都不是敲锣打鼓来的,而是隐藏在一片噪声里,马斯克给我们带来的特斯拉虽然不尽完美,但他做产品的思维和执着于未来的勇气,值得学习。埃隆•马斯克创办公司也不是为了赚钱,而是为了拯救人类和地球,电动汽车、太阳能发电、宇宙火箭,不管是哪一项都足以令一个国家付出巨大的代价去研究开发,但埃隆•马斯克却一个人在做这些......一起来看看 《乔布斯离开了,马斯克来了》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试