我试图在我的视图顶部添加一个UILabel,它可以是多行的。我已经研究过了,但我不能让它工作,因为它只会显示一行,我希望它像需要的那样大。我用自动布局来做这件事,我现在的代码是:
UILabel *label = [[UILabel alloc] init];
label.translatesAutoresizingMaskIntoConstraints = NO;
label.text = @"jklljk sdkhfdjkdsfjhkfk fhs fdh fk dksdks dfss s dfs dfs fsdkdfks dfks dfks df k dfh";
label.numberOfLines = 0;
NSDictionary *views = @{@"label" : label};
[self.view addSubview:label];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[label]|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[label(>=20)]" options:0 metrics:nil views:views]];发布于 2014-02-18 23:54:44
您需要在标签上设置一个框架,以设置其在视图中的初始位置。
查看编程指南中:
向父视图添加子视图时,子视图的当前框架矩形表示其在父视图中的初始位置。
发布于 2014-02-19 00:00:44
尝试呼叫:
[self.view layoutIfNeeded];添加约束后。这应该会用新的约束更新视图。
发布于 2014-02-19 04:30:06
如果您可以通过界面构建器添加标签,它将省去编写大量标签属性代码,尽管从您所描述的,如果您使用下面的代码(替换您想要的位置,大小和文本值),那么这个标签将根据您填充的内容而变化。我一直在用它,效果很好。
UILabel *label = [[UILabel alloc] initWithFrame:GCRectMake(0,0,300, 50)]; //these values to be changed to reflect where you want the label to appear, initial position and size, width etc.
//setting up the label attributes etc
label.numberOfLines = 0; //This means there's no limit to lines of text.
label.font = [UIFont systemFontOfSize:13];
label.textColor = [UIColor blackColor];
NSString *content = YOUR_TEXT;// your example @"jklljk sdkhfdjkdsfjhkfk fhs fdh fk dksdks dfss s dfs dfs fsdkdfks dfks dfks df k dfh";
CGSize maximumLabelSize = CGSizeMake(300, 1000); //For example - the height can be changed to any maximum value.
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13] forKey: NSFontAttributeName]; //This allows a calculation to be made of the space taken up, so if you're using a custom or large font it will calculate accordingly.
CGSize newExpectedLabelSize = [content boundingRectWithSize:maximumLabelSize options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil].size;
CGRect frame = label.frame;
frame.size.height = newExpectedLabelSize.height;
label.frame = frame; //This last line should change the height of your label according to what it needs to be to have all the text visible and over multiple lines.我希望这能帮助你找到你想要的东西。
(这也取代了对任何约束编码的需求。)
干杯,吉姆
https://stackoverflow.com/questions/21858515
复制相似问题