重写UIbutto 改变字体和图片位置



    _btnSelect = [UIButton buttonWithType:UIButtonTypeCustom];

    _btnSelect.frame = CGRectMake(0, 0, 200, 30); // --> 必须这样写 不能用其它方法适配 

    [_btnSelect setTitle:@"和值" forState:(UIControlStateNormal)];

    [_btnSelect setImage:[UIImage imageNamed:@"arrow_down2"] forState:UIControlStateNormal];

    [_btnSelect setImage:[UIImage imageNamed:@"x-w-jiantouSelect"] forState:UIControlStateSelected];

    _btnSelect.adjustsImageWhenHighlighted = NO;

    CGFloat imgWidth = _btnSelect.imageView.bounds.size.width;

    CGFloat labWidth = _btnSelect.titleLabel.bounds.size.width;

    [_btnSelect setImageEdgeInsets:UIEdgeInsetsMake(0, labWidth, 0, -labWidth)];

    [_btnSelect setTitleEdgeInsets:UIEdgeInsetsMake(0, -imgWidth, 0, imgWidth)];

    [_btnSelect addTarget:self action:@selector(btnPlaySelectAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:_btnSelect];

    

如果 要改变 图片的位置 给按钮重新赋值时  需要重新定义 图片位置


    [_btnSelect setTitle:@"三叉戟哈哈" forState:UIControlStateNormal];

    CGFloat imgWidth = _btnSelect.imageView.bounds.size.width;

    CGFloat labWidth = _btnSelect.titleLabel.bounds.size.width;

    [_btnSelect setImageEdgeInsets:UIEdgeInsetsMake(0, labWidth, 0, -labWidth)];

    [_btnSelect setTitleEdgeInsets:UIEdgeInsetsMake(0, -imgWidth, 0, imgWidth)];



第二种方法


创建一个类"DetailButton.h"继承自UIButton

@interface DetailButton : UIButton


- (instancetype)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {

        // 设置按钮的其他属性

        self.titleLabel.textAlignment = NSTextAlignmentLeft;

        self.titleLabel.font = [UIFont systemFontOfSize:16.0];

        [self setBackgroundColor:[UIColor clearColor]];

    }

    return self;

}


// 重写layoutSubviews方法,手动设置按钮子控件的位置

- (void)layoutSubviews {

    [super layoutSubviews];

    

    self.imageView.frame = CGRectMake(10, (self.frame.size.height-25)/22525);

    self.titleLabel.frame = CGRectMake(CGRectGetMaxX(self.imageView.frame)+100self.frame.size.width-CGRectGetMaxX(self.imageView.frame)-10,self.frame.size.height);

}


//使用DetailButton

DetailButton *button = [DetailButton buttonWithType:UIButtonTypeCustom];


猜你喜欢

转载自blog.csdn.net/qq_29680975/article/details/78210607