如何调整标签大小以适合文本的长度

时间:2013-06-01 01:50:39

标签: ios objective-c uilabel

我在过去的QAs中搜索了解决方案,但找不到合适的答案 有谁知道如何动态调整UILabel大小以适应文本长度?
我上传了我不想要的屏幕截图(第1行)和我想要的内容(第2行) 我很感激任何线索,建议或代码示例。谢谢。enter image description here

8 个答案:

答案 0 :(得分:13)

您正在搜索的是UILabel方法sizeToFit

我可以尝试向您解释,但知道如何使用UILabel的最佳答案是:https://stackoverflow.com/a/1054681/666479

答案 1 :(得分:6)

Xcode 8和iOS 10

使用自动布局非常容易。无需在代码中执行任何操作。

enter image description here

使用自动布局

使用自动布局固定每个标签的顶部和左侧边缘不要为宽度和高度添加约束。视图的内在内容大小将处理这个问题。

enter image description here

以下是约束的含义:

enter image description here

代码

代码没什么特别之处。无需使用sizeToFit或类似的东西。

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var labelOne: UILabel!
    @IBOutlet weak var labelTwo: UILabel!
    @IBOutlet weak var labelThree: UILabel!

    @IBAction func changeTextButtonTapped(_ sender: UIButton) {

        labelOne.text = "David"
        labelTwo.text = "met"
        labelThree.text = "her"
    }
}

注释

  • 此答案已经过Xcode 8,iOS 10和Swift 3的重新测试。
  • 如果您想要多行调整大小,请参阅my other answer
  • 感谢this answer让我走上正轨。

答案 2 :(得分:3)

使用此扩展UILabel类:

//
//  UILabelExtended.h

//
//  Created by Prateek on 6/18/11.



#import <Foundation/Foundation.h>

/*  **********************************************************************************************
        This class inherit the class UILabel and extend the features of UILabel. 
    ********************************************************************************************** */
@interface UILabelExtended : UILabel {
   __unsafe_unretained id  customDelegate;
    id  objectInfo;
    SEL selector;
}

@property (nonatomic,assign) SEL selector;;
@property (nonatomic,assign) id  customDelegate;
@property (nonatomic,retain) id  objectInfo;
@end

@interface UILabel(UILabelCategory)
- (void)setHeightOfLabel;
- (void)setWidthOfLabel;
- (void)setHeightOfLabelWithMaxHeight:(float)maxHeight;
- (void)setWidthOfLabelWithMaxWidth:(float)maxWidth ;
@end
  

UILabelExtended.m

//
//  Created by Prateek on 6/18/11.

//

#import "UILabelExtended.h"


@implementation UILabelExtended
@synthesize selector,customDelegate, objectInfo;

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if(self.selector)
        if([self.customDelegate respondsToSelector:self.selector]) {
            [self.customDelegate performSelector:self.selector withObject:self];
            return;
        }
}

- (void)dealloc {

    self.customDelegate = nil;
    self.selector = NULL;
    self.objectInfo = nil;
}
@end


@implementation UILabel(UILabelCategory)

- (void)setHeightOfLabel {
    UILabel* label = self;

    //get the height of label content
    CGFloat height = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.bounds.size.width, 99999) lineBreakMode:NSLineBreakByWordWrapping].height;
    //set the frame according to calculated height
    CGRect frame = label.frame;
    if([label.text length] > 0) {

        frame.size.height = height;
    } 
    else {
        frame.size.height = 0;
    }
    label.frame = frame;
}


- (void)setWidthOfLabel {
    UILabel* label = self;

        //get the height of label content
    CGFloat width = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(99999, label.bounds.size.height) lineBreakMode:NSLineBreakByWordWrapping].width;
        //set the frame according to calculated height
    CGRect frame = label.frame;
    if([label.text length] > 0) {

        frame.size.width = width+5;
    } 
    else {
        frame.size.width = 0;
    }
    label.frame = frame;
}

- (void)setHeightOfLabelWithMaxHeight:(float)maxHeight {
    UILabel* label = self;

    //get the height of label content
    CGFloat height = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.bounds.size.width, maxHeight) lineBreakMode:NSLineBreakByWordWrapping].height;
    //set the frame according to calculated height
    CGRect frame = label.frame;

    if([label.text length] > 0) {
        if (height > maxHeight) {
            frame.size.height = maxHeight;
        }
        else {
            frame.size.height = height;
        }

    } 
    else {
        frame.size.height = 0;
    }
    label.frame = frame;
}

- (void)setWidthOfLabelWithMaxWidth:(float)maxWidth  {
    UILabel* label = self;

    //get the height of label content
    CGFloat width = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(99999, label.bounds.size.height) lineBreakMode:NSLineBreakByWordWrapping].width;
    //set the frame according to calculated height
    CGRect frame = label.frame;
    if([label.text length] > 0) {

        if (width > maxWidth) {
            frame.size.width = maxWidth;
        }
        else {
            frame.size.width = width;
        }
    } 
    else {
        frame.size.width = 0;
    }
    label.frame = frame;
}
@end
  

使用方法:   1)设置UILabel的文本   2)[yourLBLObj setHeightOfLabel];[yourLBLObj setWidthOfLabel];   它将根据文本自动设置高度或宽度。

答案 3 :(得分:3)

您只需为字符串大小计算UILabel宽度,请尝试设置UILabel尺寸的简单代码

   // Single line, no wrapping;
    CGSize expectedLabelSize = [string sizeWithFont:yourFont];
 //  you get width,height in expectedLabelSize;
//expectedLabelSize.width,expectedLabelSize.height

答案 4 :(得分:1)

试试这个

        NSString *text1 = [NSString stringWithFormat:@"%@",commentText];
        CGSize constraint1 = CGSizeMake(280, 2000);
        CGSize size1 = [text1 sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:constraint1 lineBreakMode:UILineBreakModeWordWrap];

        UILabel *lblComment = [[UILabel alloc] initWithFrame:CGRectMake(posx,posy,size1.width,size1.height)] ;
        lblComment.lineBreakMode = UILineBreakModeWordWrap;
        lblComment.numberOfLines = size1.height/15;
        [lblComment setFont:[UIFont systemFontOfSize:12]];
        lblComment.text = text1;
        lblComment.tag = shareObjC.userId;
            [lblComment setNeedsDisplay]

答案 5 :(得分:0)

您可以使用这段代码来计算标签宽度并设置它

   CGSize expectedLabelSize = [name sizeWithFont:yourfont constrainedToSize:maximumLabelSize]; 

//您可以从expectedLabelSize获取宽度宽度高度并相应地设置

答案 6 :(得分:0)

目前我正在开发IOS-8,并且我对@Suragch做了一些小改动(需要使用自动布局来完成这项工作)

以下是结果中的步骤和屏幕截图:

  1. 将文本视图放在UIView中,而不是直接放在内容视图中 在故事板中
  2. 从故事板中禁用文本视图滚动
  3. 添加我在下面添加到视图中的前导和顶部约束 截图(尾随约束是可选的,但我已添加)
  4. 没有必要在swift中添加代码,这可以在storyboard本身中完成。

    结果:enter image description here

答案 7 :(得分:0)

您只需要输入2行代码

lbl1.numberOfLines = 0
    lbl1.sizeToFit()

它将根据内容管理标签宽度

希望它能帮助别人:)