5

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 を使用する必要があると思います。

ありがとうございました。

4

2 に答える 2

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   
于 2012-10-07T17:04:22.053 に答える