swift 自定義UIButton 圖片在上 文字在下
1 首先繼承UIButton
2 實現imageRectForContentRect titleRectForContentRect
// 內部圖片的frame
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imageW = contentRect.size.width;
CGFloat imageH = contentRect.size.height * IWTabBarButtonImageRatio;
return CGRectMake(0, 0, imageW, imageH);
}
// 內部文字的frame
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat titleY = contentRect.size.height * IWTabBarButtonImageRatio;
CGFloat titleW = contentRect.size.width;
CGFloat titleH = contentRect.size.height - titleY;
return CGRectMake(0, titleY, titleW, titleH);
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 圖示居中
self.imageView.contentMode = UIViewContentModeCenter;
// 文字居中
self.titleLabel.textAlignment = NSTextAlignmentCenter;
}
return self;
}