簡體   English   中英

UIButton在imageview下有標題

[英]UIButton with title under the imageview

我想以編程方式使用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   

最終和穩定的解決方案是使用框架,而不是像這樣的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM