2012-10-07 50 views
4

我想用imageView下的標題以編程方式創建一個UIButton。UIButton with imageview下的標題

按鈕尺寸:170 * 120 圖片尺寸:50 * 50 標題大小:依文字內容而定。

我知道I'have使用,但我不知道如何:

[_button setTitleEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)]; 
[_button setImageEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)]; 

我想我應該計算出標題的大小,然後使用EdgeInsets。

謝謝。

回答

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 
+0

看來,如果標題文本太長,即使UIButton框架有空間顯示它,它也會在中間截斷它。每次我試圖花費標題框寬度時,標題都會回到圖像本身。任何想法? – Ben

19

希望這可以幫助你。

@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 
+2

這是一個很好的答案!但我有一些問題,並改變你如何定義titleSize解決它:'CGSize titleSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font constrainedToSize:CGSizeMake(self.frame.size.width,MAXFLOAT)lineBreakMode:self.titleLabel 'lineBreakMode];' –

+2

@NatanR。,現在不推薦使用sizeWithFont,可以使用它來支持iOS7 + 'CGSize titleSize = [self.titleLabel.text sizeWithAttributes:@ {NSFontAttributeName:self.titleLabel.font}];'' by @ [chadkouse](https://gist.github.com/chadkouse) – Hemang

+0

有沒有辦法在故事板中做到這一點? – Dashrath