iPhone - 根据文字调整UILabel宽度

Dev*_*Dev 18 iphone objective-c uilabel ios

如何根据文字调整标签宽度?如果文本长度很小我想要标签宽度小......如果文本长度很小我想要标签宽度根据文本长度.可能吗?

实际上我有两个UIlabels.我需要把这两个放在附近.但如果第一个标签的文字太小,就会有很大的差距.我想消除这个差距.

NAN*_*NAV 38

//use this for custom font
CGFloat width =  [label.text sizeWithFont:[UIFont fontWithName:@"ChaparralPro-Bold" size:40 ]].width;

//use this for system font 
CGFloat width =  [label.text sizeWithFont:[UIFont systemFontOfSize:40 ]].width;

label.frame = CGRectMake(point.x, point.y, width,height);

//point.x, point.y -> origin for label;
//height -> your label height; 
Run Code Online (Sandbox Code Playgroud)

  • 在iOS 7.0中已弃用 (12认同)

Sih*_*vic 12

功能 sizeWithFont:在iOS 7.0中已弃用,因此您必须使用sizeWithAttributes:iOS 7.0+.另外,为了支持旧版本,可以使用以下代码:

    CGFloat width;
    if ([[UIDevice currentDevice].systemVersion floatValue] < 7.0)
    {
        width = [text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:16.0 ]].width;
    }
    else
    {
        width = ceil([text sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:16.0]}].width);
    }
Run Code Online (Sandbox Code Playgroud)

Apple文档推荐使用ceil()结果函数sizeWithAttributes::

"此方法返回小数大小;要使用返回的大小来调整视图大小,必须使用ceil函数将其值提升到最接近的更高整数."

sizeWithAttributes


Vin*_*yak 5

    // In swift 2.0
    let lblDescription = UILabel(frame: CGRectMake(0, 0, 200, 20))
    lblDescription.numberOfLines = 0
    lblDescription.text = "Sample text to show its whatever may be"
    lblDescription.sizeToFit()

    // Its automatically Adjust the height
Run Code Online (Sandbox Code Playgroud)