您的位置:首页 > 其它

使用setImageEdgeInSet和setTitleEdgeInSet让按钮的图片和文字垂直居中上下显示

2011-11-30 22:27 591 查看

使用setImageEdgeInSet和setTitleEdgeInSet让按钮的图片和文字垂直居中上下显示

今天完成了这个,整理为公用代码,分享一下,调用时只要设置好按钮图片和文字后,直接调用 centerImageAndTitle 即可

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: