[英]Adjusting CGSize according to the UILabel Font Size
The CGSize
which I am getting is longer in height than the label font. 我得到的CGSize
高度比标签字体长。 I want to remove the top/left/right/bottom padding between the text and the UILabel edges so that the UILabel frame just fits the text it contains. 我想删除文本和UILabel边缘之间的顶部/左侧/右侧/底部填充,以便UILabel框架恰好适合其包含的文本。
This is the code I am using.... 这是我正在使用的代码。
NSString *ad=@"hello";
NSDictionary *fontAttributes = @{NSFontAttributeName : [UIFont systemFontOfSize:50]};
CGSize textSize = [ad sizeWithAttributes:fontAttributes];
bc =[[UILabel alloc]initWithFrame:CGRectMake(20, 25, textSize.width, textSize.height)];
bc.font= [UIFont systemFontOfSize:50];
bc.text=ad;
bc.layer.borderColor = [UIColor blackColor].CGColor;
bc.layer.borderWidth = 1.0;
[self.tap addSubview:bc];
You do not have to get CGSize
textSize to allocate your UILabel
. 您不必获取CGSize
textSize即可分配UILabel
。
Using autolayout in your label: 在标签中使用自动版式:
numberOfLines
property to 0 将numberOfLines
属性设置为0 preferredMaxLayout
width in your VC(if your development target < iOS8) 在您的VC中设置preferredMaxLayout
宽度(如果您的开发目标<iOS8) You can do this by setting the property of sizeToFitContent if you have dragged it in view. 如果已将其拖动到视图中,则可以通过设置sizeToFitContent属性来实现。 Programmatically, you can try sizeToFit. 您可以通过编程方式尝试sizeToFit。
Try this: 尝试这个:
NSString *mytext = @"some random text";
UILabel *someLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 280, 100)];
someLabel.text = mytext;
someLabel.backgroundColor = [UIColor clearColor];
someLabel.lineBreakMode = NSLineBreakByWordWrapping;
[self.view addSubview:someLabel];
// For single line
someLabel.numberOfLines = 1;
someLabel.minimumScaleFactor = 8;
someLabel.adjustsFontSizeToFitWidth = YES;
// For multiple lines
someLabel.numberOfLines = 0;
someLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(someLabel.frame.size.width, CGFLOAT_MAX);
CGSize expectSize = [someLabel sizeThatFits:maximumLabelSize];
someLabel.frame = CGRectMake(someLabel.frame.origin.x, someLabel.frame.origin.y, expectSize.width, expectSize.height);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.