iOS UIButton 设置图片文字上下居中对齐
具体的实现主要代码:
- (void)centerButton:(UIButton *)button{
button.backgroundColor = [UIColor clearColor];
CGSize imageSize = button.imageView.frame.size;
CGSize titleSize = button.titleLabel.frame.size;
button.titleEdgeInsets = UIEdgeInsetsMake(8, -imageSize.width, -imageSize.height -15, 0);
button.imageEdgeInsets = UIEdgeInsetsMake(-titleSize.height -5, 0, 0, -titleSize.width);
}
但是如果你设置了按钮的frame的时候,而且button的宽度不足以同时显示图片和文字的大小的话,titleLabel的size将会获取错误。所以如果需要设置frame,建议先将button的宽度设置比你想要的大点(比如:2倍), 等titleEdgeInsets和imageEdgeInsets全部设置完成以后再重新设置frame。
具体调用代码:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 100, 60);//实际想要宽度50。设置100
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
button.titleLabel.font = [UIFont systemFontOfSize:12];
[button setTitle:obj forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:imageArray[idx]] forState:UIControlStateNormal];
[self centerButton:button];
button.frame = CGRectMake(0, 0, 50, 60);//重新设置一遍 50