iOS 按钮的内容上下居中

第一次遇到一个按钮需要 图片和文字上下居中,先反复设置了titleEdgeInsets 和 imageEdgeInsets,直到肉眼看来居中了
下一次又遇到这个需求,发现还要猜这两个属性 上下左右的间距
果断受不了了,直接在按钮里面add imageview 和 label,用这个方法来写,frame不是问题了。
下一次再遇到这个问题,不过又多了个需求,需要有高亮和选择的状态显示,我x 还得监听父控件的状态来改变子控件的显示
这回,感觉要死磕了
找了下文档和一些文章
对 titleEdgeInsets 和 imageEdgeInsets,contentEdgeInsets 有了更清晰的了解
然后写了个unbutton的分类

废话不多说,直接上代码

  • (UIButton *)ButtonWithFont:(CGFloat )font image:(NSString *)image imageH:(NSString *)imageH imageSlected:(NSString *)imageSlected title:(NSString *)title imageCenterRatio:(CGFloat )imageRatio titleCenterRatio:(CGFloat )titleRatio {

    UIButton *btn = [[UIButton alloc] init];
    UIImage *btnImage = [UIImage imageNamed:image];
    CGFloat imageWidth = CGImageGetWidth(btnImage.CGImage);
    CGFloat imageHeight = CGImageGetHeight(btnImage.CGImage);

    if ([UIScreen mainScreen].scale == 3.0f) {
    imageWidth *= 0.5f;
    imageHeight *= 0.5f;
    }

    NSString *btnText = title;
    UIFont *btnFont = [UIFont systemFontOfSize:font];
    NSDictionary *attrs = @{NSFontAttributeName : btnFont};
    CGSize labelSize = [btnText boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options: NSStringDrawingTruncatesLastVisibleLine attributes:attrs context:nil].size;

    CGFloat labelHeight = labelSize.height;
    CGFloat labelWidth = labelSize.width;

    CGFloat btnH = imageHeight + labelHeight;
    CGFloat btnW = imageWidth + labelWidth;

    btn.bounds = CGRectMake(0, 0, btnW, btnH);

[btn setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:imageH] forState:UIControlStateHighlighted];
[btn setImage:[UIImage imageNamed:imageSlected] forState:UIControlStateSelected];

[btn setTitle:title forState:UIControlStateNormal];
[btn.titleLabel setFont:[UIFont systemFontOfSize:font]];

CGPoint imageEndCenter = CGPointMake(btnW / 2, btnH * imageRatio);
CGPoint imageStartCenter = btn.imageView.center;

CGFloat top1 = imageEndCenter.y - imageStartCenter.y;
CGFloat left1 = imageEndCenter.x - imageStartCenter.x;
CGFloat bottom1 = -top1;
CGFloat right1 = -left1;
btn.imageEdgeInsets = UIEdgeInsetsMake(top1, left1, bottom1, right1);

CGPoint titleEndCenter = CGPointMake(btnW / 2, btnH * titleRatio);
CGPoint titleStartCenter = btn.titleLabel.center;

CGFloat top2 = titleEndCenter.y - titleStartCenter.y;
CGFloat left2 = titleEndCenter.x - titleStartCenter.x;
CGFloat bottom2 = -top2;
CGFloat right2 = -left2;

btn.titleEdgeInsets = UIEdgeInsetsMake(top2, left2, bottom2, right2);
btn.contentEdgeInsets = UIEdgeInsetsMake(0, -labelWidth/2, 0, -labelWidth/2);



return btn;

}

你可能感兴趣的:(iOS 按钮的内容上下居中)