【问题标题】:How to change the width of label once after its frame has been set? and to get the width of NSString设置框架后如何更改标签的宽度?并获得 NSString 的宽度
【发布时间】:2012-11-09 10:47:08
【问题描述】:

希望你做得很好。

我正在设置一个标签并调整它的框架..

UILabel *mylabel=[[UILabel alloc]init];
    mylabel.Text=@"This is my label";
    mylabel.frame=CGRectMake(10,10,200,21);

现在,如果我像这样从我设置的任何字符串中更改标签的文本

NSString *mystring=@"This is my first string that is to be assigned to my label dynamilcally";
mylabel.Text=mystring;
mylabel.frame.size.width=mystring.length;

但什么也没发生。标签的宽度保持 200,正如我在初始化时设置的那样。

这还需要获取 mystringwidth 。如何获得?

非常感谢您对我的帮助。

【问题讨论】:

    标签: objective-c ios6 uilabel xcode4.5


    【解决方案1】:

    [myLabel sizeToFit] 如果你需要它在一行。对于多行标签,您可以使用NSStringsizeWithFont:constrainedToSize:lineBreakMode: 函数来获取字符串的大小并使用它来修改标签的高度和宽度。

    例如为您提供固定宽度为 200px 的多行标签的高度的代码:

    CGSize textSize = { 
        200.0,   // limit width
        20000.0  // and height of text area
    }; 
    
    CGSize size = [descriptionString sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = size.height < 36? 36: size.height; // lower bound for height
    
    CGRect labelFrame = [myLabel frame];
    labelFrame.size.height = height;
    [myLabel setFrame:labelFrame];
    [myLabel setText:descriptionString];
    

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-09
      相关资源
      最近更新 更多