UILabel可以设置左对齐、右对齐和居中,那如何实现上下对齐呢?

有几种方案:

1.简单粗暴,在文本后面加多一些\n。但是\n后还得加至少一个空格,否则多余的\n会被UILabel忽略。

2.自定义UILabel,重写- (void)drawTextInRect:(CGRect)rect;
下面是代码

- (void)drawTextInRect:(CGRect) rect
{
    NSAttributedString *attributedText = [[NSAttributedString alloc]     initWithString:self.text attributes:@{NSFontAttributeName:self.font}];
    rect.size.height = [attributedText boundingRectWithSize:rect.size
                                                    options:NSStringDrawingUsesLineFragmentOrigin
                                                    context:nil].size.height;
    if (self.numberOfLines != 0) {
        CGFloat textHeight = MIN(rect.size.height, self.numberOfLines * self.font.lineHeight);
/*****
 打开这句话即为下对齐
 rect.origin.y = self.frame.size.height - textHeight;
 *****/
        rect.size.height = textHeight;
    }
    [super drawTextInRect:rect];
}

 

 就这么简单!

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-24
猜你喜欢
  • 2021-07-20
  • 2021-10-23
  • 2021-05-20
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案