iOS 按钮的图片文字居中和左字右图

创建一个子类Button继承自UIButton

- (void)awakeFromNib{
    
    [super awakeFromNib];
    [self setButtonContentCenter:self];
    //[self setButtonContentLeft];  根据需要与上面的方法二选其一
    //写在这里的作用是 xib画的button 选择这个类 会自动调整位置
    //如果想影响代码创建的button需要重写对应构造函数
}

-(void)setHighlighted:(BOOL)highlighted{

  //重写父类方法 会导致点击没有高亮
}

- (void)setSelected:(BOOL)selected{
    
    [super setSelected:selected];
    
    [self setButtonContentCenter:self];
     //[self setButtonContentLeft];
}

//设置图片在中上 文字在中下
-(void)setButtonContentCenter:(UIButton *) btn

{
    
    CGSize imgViewSize,titleSize,btnSize;
    
    UIEdgeInsets imageViewEdge,titleEdge;
    
    //设置按钮内边距
    
    imgViewSize = btn.imageView.bounds.size;
    
    titleSize = btn.titleLabel.bounds.size;
    
    btnSize = btn.bounds.size;
    
    CGFloat heightSpace = btnSize.height / 2.0 - imgViewSize.height;
    
    
    imageViewEdge = UIEdgeInsetsMake(heightSpace,0.0, btnSize.height - imgViewSize.height - heightSpace, - titleSize.width);
    
    [btn setImageEdgeInsets:imageViewEdge];
    
    titleEdge = UIEdgeInsetsMake(imgViewSize.height + heightSpace, - imgViewSize.width, 0.0, 0.0);
    
    [btn setTitleEdgeInsets:titleEdge];
    
}
//设置文字在左图片在右
-(void)setButtonContentLeft:(UIButton *) btn

{
    
    CGSize imgViewSize,titleSize,btnSize;
    
    //设置按钮内边距
    
    imgViewSize = btn.imageView.bounds.size;
    
    titleSize = btn.titleLabel.bounds.size;
    
    btnSize = btn.bounds.size;
    
    [self setTitleEdgeInsets:UIEdgeInsetsMake(0, -imgViewSize.width - 2, 0, imgViewSize.width + 2)];
    [self setImageEdgeInsets:UIEdgeInsetsMake(0, titleSize.width + 2, 0, - titleSize.width - 2)];
    
    
}

你可能感兴趣的:(iOS 按钮的图片文字居中和左字右图)