在UIButton上将图像的位置与标题的长度分开

时间:2014-08-19 10:02:43

标签: ios objective-c uiimageview uibutton uiimage

UIButton图像位置取决于同一图像的当前标题长度。

如果没有标题集,则第一个UIButton图像居中。 当有一个时,第二个向左移动("喜欢")。

Thumb image is centered if there is no title set Thumb image is shifted to the right when a title is set

如何始终将UIButton图像保留在按钮的中央?即使标题出现在它的顶部?

我已经尝试过使用imageInset,这也是同样的问题。我也不想使用除默认UIButton之外的其他UIImageView。

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码...

// the space between the image and text
CGFloat spacing = 6.0;

// lower the text and push it left so it appears centered 
//  below the image
CGSize imageSize = button.imageView.frame.size;
button.titleEdgeInsets = UIEdgeInsetsMake(
  0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);

// raise the image and push it right so it appears centered
//  above the text
CGSize titleSize = button.titleLabel.frame.size;
button.imageEdgeInsets = UIEdgeInsetsMake(
  - (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);

来源:UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

您可以使用以下链接

尝试其他解决方案

UIButton Image + Text IOS

希望它对你有所帮助......