button设置:图上文字下

1. 一开始我的方案

自定义类继承UIButton,然后

-(void)layoutSubviews{    [superlayoutSubviews];CGFloatmidX =self.frame.size.width/2;CGFloatmidY =self.frame.size.height/2;self.titleLabel.center=CGPointMake(midX, midY +15);self.imageView.center=CGPointMake(midX, midY -10);}

效果嘛,还不错,现在开发的项目中一直在用。但是心里总感觉这样有点旁门左道的样子,于是乎就有了下边的另外一种实现。


2. 之后试了好多次得到的结果

UIButton添加扩展

- (void)verticalImageAndTitle:(CGFloat)spacing{

self.titleLabel.backgroundColor =  [UIColorgreenColor];

CGSizeimageSize = self.imageView.frame.size;

CGSizetitleSize = self.titleLabel.frame.size;

CGSizetextSize = [self.titleLabel.textsizeWithFont:self.titleLabel.font];

CGSizeframeSize =CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));

if(titleSize.width+0.5< frameSize.width) {   

    titleSize.width= frameSize.width;   

}

CGFloattotalHeight = (imageSize.height+ titleSize.height+ spacing);

self.imageEdgeInsets=UIEdgeInsetsMake(- (totalHeight - imageSize.height),0.0,0.0, - titleSize.width);

self.titleEdgeInsets=UIEdgeInsetsMake(0, - imageSize.width, - (totalHeight - titleSize.height),0);


原文链接:http://www.jianshu.com/p/778aac34926a

你可能感兴趣的:(button设置:图上文字下)