填充边框宽度的 UILabel 文本 [英] UILabel text to fill in the frame width

查看:33
本文介绍了填充边框宽度的 UILabel 文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 UILabel 制作排版海报

I want to build typography poster using UILabel

  • 左边距和边距:25
  • 320(设备宽度) - 50(边距总和)= 270(标签宽度框架)

每个标签的字体大小应该改变以适应 270 帧宽度

The font size of each label should change in order to fit in 270 frame width

我尝试使用 sizeToFit(),adjustsFontSizeToFitWidth=true

var margin = 0;
let label = UILabel(frame: CGRectMake(25 , 72, 270, 70));
label.backgroundColor = UIColor.clearColor();
label.textAlignment = NSTextAlignment.Left;
label.textColor = UIColor.blackColor();
label.numberOfLines = 1;
label.font = UIFont.systemFontOfSize(50.0);
label.text = "Some Text";
label.adjustsFontSizeToFitWidth = true;
self.view.addSubview(label);
margin += 60;

let label2 = UILabel(frame: CGRectMake(25 , CGFloat(72+margin), 270, 70));
label2.backgroundColor = UIColor.clearColor();
label2.textAlignment = NSTextAlignment.Left;
label2.textColor = UIColor.whiteColor();
label2.numberOfLines = 1;
label2.font = UIFont.boldSystemFontOfSize(45.0);
label2.text = "Some Text Longer";
self.view.addSubview(label2);

label1 和 label2 adjustsFontSizeToFitWidth=true 时的截图

Screenshot when lable1 and label2 adjustsFontSizeToFitWidth=true

文本应该从第一个灰色边框的末尾开始,在第二个灰色边框的开头结束

The text should start from the end of first grey border and end in the beginning at the start of the second grey border

推荐答案

adjustsFontSizeToFitWidth 不会增加标签中的字体大小以适应宽度.

adjustsFontSizeToFitWidth does not increase the size of the font in the label to fit the width.

根据 Apple 的文档,

According to Apple's documentation,

adjustsFontSizeToFitWidth 是一个布尔值,表示应减小字体大小以使标题字符串适合标签的边界矩形.

adjustsFontSizeToFitWidth is a Boolean value indicating whether the font size should be reduced in order to fit the title string into the label’s bounding rectangle.

通常情况下,标签文本使用您在字体属性.但是,如果此属性设置为 YES,并且文本在 text 属性超出标签的边界矩形时,接收器开始减小字体大小,直到字符串适合或已达到最小字体大小.在 iOS 6 及更早版本中,此属性为仅当 numberOfLines 属性设置为 1 时有效.

Normally, the label text is drawn with the font you specify in the font property. If this property is set to YES, however, and the text in the text property exceeds the label’s bounding rectangle, the receiver starts reducing the font size until the string fits or the minimum font size is reached. In iOS 6 and earlier, this property is effective only when the numberOfLines property is set to 1.

您可以尝试增加字体大小以适应框架的宽度.

来源:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instm/UIView/sizeToFit

你也可以用下面的方法迭代找到适合标签的最大尺寸.

如何调整标签的字体大小适合矩形?

这篇关于填充边框宽度的 UILabel 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆