我试图根据字符串和字体大小想出一种方法来知道UILabel的大小,从而知道如何定义CGRect尺寸。
在这里,我直到知道:
UILabel *myLabel = [[UILabel alloc] init];
myLabel.font = [UIFont fontWithName:@"BentonSansComp-Medium" size:50.0];
myLabel.text = @"This is a string example"
问题是我没有可能的字符串列表,但是需要将标签居中,并且字符串不应该被切碎(使用上面的例子:“This is a str ....”)。你们谁都知道如何根据字符串和字体大小确定UILabel的大小?
非常感谢您的帮助。
最佳答案
只需使用
UILabel *myLabel = [[UILabel alloc] init];
myLabel.font = [UIFont fontWithName:@"BentonSansComp-Medium" size:50.0];
myLabel.text = @"This is a string example"
[myLabel sizeToFit]; //it will resize the label to just the text is set
CGRectMake size = myLabel.frame; // u will get the frame of the label once is resized
float height = size.size.height; //to get the height of the label
float width = size.size.width; //to get the width of the label
希望能帮助到你确保每次更改文本时都调用[myLabel sizeToFit];方法
关于iOS如何动态确定UILabel的大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21611234/