如何让UILabel字体上下对齐?
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]; }
就这么简单!