UIButton在imageview下有标题

Ala*_*lak 5 text image uibutton ios uiedgeinsets

我想以编程方式使用imageView下的标题创建一个UIButton.

按钮大小:170*120图片大小:50*50标题大小:取决于文字.

我知道我要使用,但我不知道如何:

[_button setTitleEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)];
[_button setImageEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)];
Run Code Online (Sandbox Code Playgroud)

我想我应该计算标题的大小然后使用EdgeInsets.

谢谢.

usp*_*hon 20

希望这可以帮到你.

@interface UIButton (UIButtonExt)  

- (void)centerImageAndTitle:(float)space;  
- (void)centerImageAndTitle;  

@end  

@implementation UIButton (UIButtonExt)  

- (void)centerImageAndTitle:(float)spacing  
{      
    // get the size of the elements here for readability  
    CGSize imageSize = self.imageView.frame.size;  
    CGSize titleSize = self.titleLabel.frame.size;  

    // get the height they will take up as a unit  
    CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);  

    // raise the image and push it right to center it  
    self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);  

    // lower the text and push it left to center it  
    self.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (totalHeight - titleSize.height),0.0);      
}  

- (void)centerImageAndTitle  
{  
    const int DEFAULT_SPACING = 6.0f;  
    [self centerImageAndTitle:DEFAULT_SPACING];  
}  

@end   
Run Code Online (Sandbox Code Playgroud)

  • @NatanR.,因为现在不推荐使用sizeWithFont,可以使用它来支持iOS7 +`CGSize titleSize = [self.titleLabel.text sizeWithAttributes:@ {NSFontAttributeName:self.titleLabel.font}];`by @ [chadkouse](https: //gist.github.com/chadkouse) (3认同)
  • 这是一个非常好的答案!但是我遇到了一些问题并改变了你定义titleSize的方法:`CGSize titleSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font constrainedToSize:CGSizeMake(self.frame.size.width,MAXFLOAT)lineBreakMode:self.titleLabel .lineBreakMode];` (2认同)

小智 4

最终稳定的解决方案是使用框架,而不是EdgeInset像这样的解决方案:

@interface UIButton (UIButtonExt)
(void)centerImageAndTitleEx;
@end

@implementation UIButton (UIButtonExt)

(void)centerImageAndTitleEx
{
CGRect frame = self.imageView.frame;

frame = CGRectMake(truncf((self.bounds.size.width - frame.size.width) / 2), 10.0f, frame.size.width, frame.size.height);

self.imageView.frame = frame;

frame = self.titleLabel.frame;

frame = CGRectMake(truncf((self.bounds.size.width - frame.size.width) / 2), self.bounds.size.height - frame.size.height - 5.0, frame.size.width, frame.size.height);

self.titleLabel.frame = frame;
}

@end
Run Code Online (Sandbox Code Playgroud)