objective-c - UILabel 不会调整大小

标签 objective-c cocoa uilabel uitextview sizetofit

我的 View 中有 UILabel,它应该根据内容调整自身大小,但它没有这样做。我里面有多行内容。我尝试了 [label sizeToFit] + label.numberOfLines= 0

我对 UILabel 没有限制。

我也尝试使用 UITextView 代替,但字体只是停留在 13,而不是我想要的 17。你能帮助我吗?

这是现在可以运行的代码:

UILabel *textLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 158, self.view.bounds.size.width-40, 550)];
textLabel2.text = textString;
textLabel2.font = [UIFont fontWithName:@"Helvetica Neue" size:17];
textLabel2.numberOfLines = 0;
[textLabel2 sizeToFit];
[self.scroller addSubview:textLabel2];

最佳答案

如果您以编程方式创建 UILabel:

此代码首先设置UIlabel的文本,然后获取文本的宽度

UILabel *label = [[UILabel alloc] init];
//set label backgroundColor so you can see the label width changes according to text
[label setBackgroundColor:[UIColor redColor]];
//edit you label text
[label setText:@"very longgggg text"];

//get width of you text and set you font size to 17.0
CGFloat width =  [label.text sizeWithFont:[UIFont systemFontOfSize:17.0f]].width;

//set you label frame
label.frame = CGRectMake(10, 200, width, 30);

//add label to you view
[self.view addSubview:label];

如果您不以编程方式创建 UILabel,请删除 alloc init 行并将您的导出连接到 xib 或 Storyboard。

关于objective-c - UILabel 不会调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25448267/

相关文章:

ios - 应用程序 :didReceiveRemoteNotification:fetchCompletionHandler Not Called

ios - Q : Custom TableViewCell scroll to not see, 并再次显示,我的自定义行关闭

ios - 以编程方式设置 UILabel 高度 Swift 不起作用

ios - 通过 UIViewRepresentable 在 SwiftUI 中调整 UILabel 的大小,如 Text 以包裹多行

iphone - 将 UINavigationBar 背景图像更改为默认 - iOS 4.3

objective-c - iOS readonly 和 retain 是互斥的

xcode - 在cocoa应用程序中创建菜单和子菜单

objective-c - NSLog 在我幸运的 HelperTool 中不起作用

cocoa - 什么时候 initWithFormat :arguments: be used?

iphone - 如何向 UILabel 添加反射。 IOS