以前不怎么有这样的需求,最近开发经常用到,所以就干脆封装一个这样的 Button 让图片和字体都垂直居中,重写layoutSubviews方法,来实现就可以,至于 layoutSubviews 方法什么时候触发,可以自行查下;
- (instancetype)initWithCoder:(NSCoder *)coder{ self = [super initWithCoder:coder]; if (self) { self.layer.shadowColor = [UIColor lightGrayColor].CGColor; self.layer.shadowOffset = CGSizeMake(0, 1); 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)/2, VIEWHEIGHT(self)/2 - imgHeight*7/7,imgWidth, imgHeight); //titleLabel的尺寸 [self.titleLabel sizeToFit]; float titleWidth = VIEWWIDTH(self.titleLabel); float titleHeight = VIEWHEIGHT(self.titleLabel); self.titleLabel.frame = CGRectMake((VIEWWIDTH(self) - titleWidth)/2, VIEWHEIGHT(self)/2 + imgHeight/7 + 20*VIEWHEIGHT(self)/900, titleWidth, titleHeight); self.titleLabel.textAlignment = NSTextAlignmentCenter; }