iOS-Button圖片和文字垂直置中【按鈕圖片和文字同時置中】,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(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;}