以编程方式创建UILabel

35

我知道这应该很简单,但我一直在努力通过编程方式创建UILabel并使其按照我想要的方式运行。

我想做的就是创建一个标签,将最大属性设置为高度、宽度和字体大小,然后让文本变小和/或截断文本以适应长字符串。

假设我想让我的标签的文本具有最大宽度为380、最大高度为20和最大字体大小为12。

因此,这是我尝试创建这样一个标签的方法:

UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, 0, 0)];
fromLabel.text = [self fromSender];
fromLabel.font = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font
fromLabel.numberOfLines = 1;
fromLabel.baselineAdjustment = YES;
fromLabel.adjustsFontSizeToFitWidth = YES;
fromLabel.adjustsLetterSpacingToFitWidth = YES;
fromLabel.size = [fromLabel.text sizeWithFont:fromLabel.font constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail];
fromLabel.minimumScaleFactor = MIN_SCALE_FACTOR;
fromLabel.clipsToBounds = YES;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor blackColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[collapsedViewContainer addSubview:fromLabel];

好的,标签出现了,但文本比12号字体更大,高度总是21?即使我将高度和文字大小值更改为极端尺寸,该代码也会创建一个固定大小的标签,无法调整。唯一能缩小的是宽度。

我一定忽略了一些基本的东西,但我真的无法弄清楚如何获得我想要的结果,也不知道为什么会出现这种行为。


你打算使用的最小字体大小是多少? - Rui Peres
最小字体大小为10,且MIN_SCALE_FACTOR = 10/12。 - jac300
大小不是只读属性吗?您可能想在这里使用框架。 - Nerkatel
8个回答

57

以下操作是否有效?

UIFont * customFont = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font
NSString * text = [self fromSender];

CGSize labelSize = [text sizeWithFont:customFont constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail];

UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, labelSize.width, labelSize.height)];
fromLabel.text = text;
fromLabel.font = customFont;
fromLabel.numberOfLines = 1;
fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; // or UIBaselineAdjustmentAlignCenters, or UIBaselineAdjustmentNone
fromLabel.adjustsFontSizeToFitWidth = YES;
fromLabel.adjustsLetterSpacingToFitWidth = YES;
fromLabel.minimumScaleFactor = 10.0f/12.0f;
fromLabel.clipsToBounds = YES;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor blackColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[collapsedViewContainer addSubview:fromLabel];

编辑:我认为您可能会遇到使用adjustsFontSizeToFitWidthminimumScaleFactor的问题。前者说明您还需要设置minimumFontWidth(否则根据我的测试,它可能缩小到难以阅读的程度),但这已过时,被后者取代。

编辑2:算了吧,文档已经过时了。 adjustsFontSizeToFitWidth需要minimumScaleFactor,只需确保不将0作为minimumScaleFactor传递(整数除法,10/12返回0)。 baselineAdjustment值也有小改动。


我认为它应该可以,但是使用上述代码,标签甚至都没有出现。 - jac300
明白了。将MIN_SCALE_FACTOR更改为10.0f/12.0f。 - Nerkatel
仍然没有出现在视图中。我尝试注释掉之前代码中的所有“adjustsTo...”,但仍然存在相同的原始问题。 - jac300
1
sizeWithFont:constrainedToSize:lineBreakMode 在 IOS 7.0 中已被弃用。 - Progo
1
@Nerkatel 你好,我在你的回答中添加了文档链接。如果你认为我在这里越界了,你可以点击回滚。谢谢。 - NSNoob
显示剩余5条评论

15
UILabel *lbl1 = [[UILabel alloc] init];
/*important--------- */lbl1.textColor = [UIColor blackColor];
[lbl1 setFrame:position];
lbl1.backgroundColor=[UIColor clearColor];
lbl1.textColor=[UIColor whiteColor];
lbl1.userInteractionEnabled=NO;
lbl1.text= @"TEST";
[self.view addSubview:lbl1];

7
这里是如何通过编程方式创建UILabel的方法。
1)在您的项目的.h文件中写入以下代码。
UILabel *label;

2) 将以下代码写入你项目的 .m 文件中。

label=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];//Set frame of label in your viewcontroller.
[label setBackgroundColor:[UIColor lightGrayColor]];//Set background color of label.
[label setText:@"Label"];//Set text in label.
[label setTextColor:[UIColor blackColor]];//Set text color in label.
[label setTextAlignment:NSTextAlignmentCenter];//Set text alignment in label.
[label setBaselineAdjustment:UIBaselineAdjustmentAlignBaselines];//Set line adjustment.
[label setLineBreakMode:NSLineBreakByCharWrapping];//Set linebreaking mode..
[label setNumberOfLines:1];//Set number of lines in label.
[label.layer setCornerRadius:25.0];//Set corner radius of label to change the shape.
[label.layer setBorderWidth:2.0f];//Set border width of label.
[label setClipsToBounds:YES];//Set its to YES for Corner radius to work.
[label.layer setBorderColor:[UIColor blackColor].CGColor];//Set Border color.
[self.view addSubview:label];//Add it to the view of your choice. 

我知道这是老问题,但是如何将框架放置在视图底部,紧靠UIToolBar上方?我希望宽度根据字符串长度自动扩展,或者如果太长则调整字体大小。 - Jonathan Weinraub

3

Swift 3:

let label = UILabel(frame: CGRect(x:0,y: 0,width: 250,height: 50))
label.textAlignment = .center
label.textColor = .white
label.font = UIFont(name: "Avenir-Light", size: 15.0)
label.text = "This is a Label"
self.view.addSubview(label)

2
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = @"Your Text";
[self.view addSubview:label];

1
In Swift -

var label:UILabel = UILabel(frame: CGRectMake(0, 0, 70, 20))
label.center = CGPointMake(50, 70)
label.textAlignment = NSTextAlignment.Center
label.text = "message"
label.textColor = UIColor.blackColor()
self.view.addSubview(label)

0

关于 Swift

var label = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 50))
label.textAlignment = .left
label.text = "This is a Label"
self.view.addSubview(label)

-1
UILabel *mycoollabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];
mycoollabel.text=@"I am cool";

// for multiple lines,if text lenght is long use next line
mycoollabel.numberOfLines=0;
[self.View addSubView:mycoollabel];

1
这可能解决问题,但最好加上一些说明它是如何/为什么起作用的。 - Holloway

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接