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;
}
复制代码

 

posted @   macroK  阅读(926)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示