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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16868298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:45:51  来源:igfitidea点击:

How to adjust a label size to fit the length of the text

iosobjective-cuilabel

提问by boochan224

I have searched the solution to this in the past QAs, but could not find the right one.
Does anyone know how to adjust aUILabelsize dynamically to fit the text length?
I have uploaded the screen shot of what I don't want(1st line) and what I want(2nd line).
I'd appreciate any clues, advice or code sample. Thank you.enter image description here

我在过去的 QA 中搜索了此问题的解决方案,但找不到合适的解决方案。
有谁知道如何UILabel动态调整大小以适应文本长度?
我已经上传了我不想要的(第一行)和我想要的(第二行)的屏幕截图。
我很感激任何线索、建议或代码示例。谢谢你。在此处输入图片说明

回答by ggrana

What you are searching is the UILabel method sizeToFit

您正在搜索的是 UILabel 方法 sizeToFit

I can try to explain to you, but the best answer to know how to work with UILabel is that: https://stackoverflow.com/a/1054681/666479

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

回答by Suragch

Xcode 8 and iOS 10

Xcode 8 和 iOS 10

This is quite easy to do with Auto Layout. No need to do anything in code.

使用自动布局很容易做到这一点。无需在代码中执行任何操作。

enter image description here

在此处输入图片说明

Use Auto Layout

使用自动布局

Use auto layout to pin each label's top and left edges only. Don't add constraints for the width and height.The view's intrinsic content size will take care of that.

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

enter image description here

在此处输入图片说明

Here is what the constraints look like:

下面是约束的样子:

enter image description here

在此处输入图片说明

Code

代码

There is nothing at all special about the code. No need to use sizeToFitor anything like that.

代码没有什么特别之处。不需要使用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"
    }
}

Notes

笔记

  • This answer has been retested with Xcode 8, iOS 10, and Swift 3.
  • See my other answerif you want multi-line resizing.
  • Thanks to this answerfor setting me on the right track.
  • 这个答案已经用 Xcode 8、iOS 10 和 Swift 3 重新测试过。
  • 如果您想要多行调整大小,请参阅我的其他答案
  • 感谢这个答案让我走上了正确的轨道。

回答by Prateek Prem

Use This Extended UILabelclass:

使用这个扩展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

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

Use Methods: 1) set text of UILabel2) [yourLBLObj setHeightOfLabel];or [yourLBLObj setWidthOfLabel];It will automatically set Height or Width according to text.

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

回答by NANNAV

you get simply calculate UILabelwidth for string size,try this simple code for set UILabelsize

你可以简单地计算UILabel字符串大小的宽度,试试这个简单的代码来设置UILabel大小

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

回答by SAMIR RATHOD

try this

尝试这个

        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]

回答by the1pawan

You can use this piece of code for calculate label width and set it

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

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

// you can get width width height from expectedLabelSize and set accordingly

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

回答by KOTIOS

Currently i m working on IOS-8 and there is small changes i made to @Suragch answer (Need to use auto layout to make this work)

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

Below is the step and screenshot in result :

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

  1. Place the textview inside UIView and not directly inside content-view in storyboard
  2. Disable scroll of textview from storyboard
  3. Add Leading and top constraints as i have added to view in below screenshot(Trailing constraint is optional but i have added )
  1. 将 textview 放在 UIView 中,而不是直接放在故事板的 content-view 中
  2. 从故事板禁用文本视图滚动
  3. 添加前导和顶部约束,因为我在下面的屏幕截图中添加了视图(尾随约束是可选的,但我已添加)

There is no need to add code in swift this can be done in storyboard itself.

无需在 swift 中添加代码,这可以在故事板本身中完成。

Result : enter image description here

结果 : 在此处输入图片说明

回答by Anjali jariwala

All you need to just put 2 lines code

您只需要输入 2 行代码

lbl1.numberOfLines = 0
    lbl1.sizeToFit()

It will manage label width as per its content

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

Hope it helps others :)

希望它可以帮助其他人:)