ios - ImageView 下带有标题的 UIButton

标签 ios image text uibutton 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)];

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

谢谢。

最佳答案

希望对您有所帮助。

@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   

关于ios - ImageView 下带有标题的 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12770751/

相关文章:

ios - 特殊UIlabel设计

ios - 如何以编程方式在 iOS 中并排制作两个 UILabel

iOS : AVFoundation Image Capture Dark

python - 分解 Pandas 数据框列

html - 如何获取html页面的 "Text"? (网络浏览器 - 德尔福)

ios - 如何让 UITextField 宽度在您键入时调整为文本?

iphone - ARC 语义问题 : No Visible @Interface for 'UIViewController' declares the selector 'loginResult:'

IOS img 不显示

r - 为什么 R 制作的这张图像中有一条虚假的垂直白线?

text - 始终显示滚动条 - Flutter