美文网首页
如何使UIButton的image和title同时居中

如何使UIButton的image和title同时居中

作者: 烟影很美 | 来源:发表于2016-05-04 16:56 被阅读389次

UIButton的image(不是backgroundImageView)和title是不重叠的, 但是使用backgroundImage又不够灵活. 这里是使用继承实现UIButton的image和title同时居中的方法.
继承UIButton, 在.m文件中写如下代码


#import "ZYCenterButton.h"

@implementation ZYCenterButton

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return self;
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect {
    CGRect frame = contentRect;
    frame.origin.x = self.frame.size.width/2 - frame.size.width/2;
    frame.origin.y = self.frame.size.height/2 - frame.size.height/2;
    return frame;
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    CGRect frame = contentRect;
    frame.origin.x = self.frame.size.width/2 - frame.size.width/2;
    frame.origin.y = self.frame.size.height/2 - frame.size.height/2;
    return frame;
}

@end

效果如下(和气泡没有半毛钱关系, 我只找到这张图好看点):

80A5D7D5-98E5-4D85-8701-C72A9FDD88FC.png

相关文章

网友评论

      本文标题:如何使UIButton的image和title同时居中

      本文链接:https://www.haomeiwen.com/subject/zagrrttx.html