iOS-Button图片和文字垂直居中【按钮图片和文字同时居中】

时间:2023-03-08 22:01:20

iOS-Button图片和文字垂直居中【按钮图片和文字同时居中】

以前不怎么有这样的需求,最近开发经常用到,所以就干脆封装一个这样的 Button 让图片和字体都垂直居中,重写layoutSubviews方法,来实现就可以,至于 layoutSubviews 方法什么时候触发,可以自行查下;

- (instancetype)initWithCoder:(NSCoder *)coder{
self = [super initWithCoder:coder];
if (self) {
self.layer.shadowColor = [UIColor lightGrayColor].CGColor;
self.layer.shadowOffset = CGSizeMake(, );
self.layer.shadowOpacity = 0.1; }
return self;
}
//重写该方法 有些比例可以自行调节
-(void)layoutSubviews{
[super layoutSubviews];
//计算宽高
float imgHeight = self.imageView.image.size.height;
float imgWidth = self.imageView.image.size.width;
//imageView的尺寸
self.imageView.frame = CGRectMake((VIEWWIDTH(self) - imgWidth)/, VIEWHEIGHT(self)/ - imgHeight*/,imgWidth, imgHeight);
//titleLabel的尺寸
[self.titleLabel sizeToFit];
float titleWidth = VIEWWIDTH(self.titleLabel);
float titleHeight = VIEWHEIGHT(self.titleLabel);
self.titleLabel.frame = CGRectMake((VIEWWIDTH(self) - titleWidth)/, VIEWHEIGHT(self)/ + imgHeight/ + *VIEWHEIGHT(self)/, titleWidth, titleHeight);
self.titleLabel.textAlignment = NSTextAlignmentCenter;
}