当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS-Button图片和文字垂直居中【按钮图片和文字同时居中】

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

2018年03月10日  | 移动技术网IT编程  | 我要评论

梦幻西游伏魔录5.1,南京品浪渔具,斗鱼tv陈一发

 

以前不怎么有这样的需求,最近开发经常用到,所以就干脆封装一个这样的 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;
}

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网