【问题标题】:How to adjust a label size to fit the length of the text如何调整标签大小以适合文本的长度
【发布时间】:2013-05-27 22:12:08
【问题描述】:

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

【问题讨论】:

    标签: ios objective-c uilabel


    【解决方案1】:

    你搜索的是UILabel方法sizeToFit

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

    【讨论】:

      【解决方案2】:

      Xcode 8 和 iOS 10

      使用自动布局很容易做到这一点。无需在代码中做任何事情。

      使用自动布局

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

      这是约束的样子:

      代码

      代码没有什么特别之处。无需使用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 让我走上正轨。

      【讨论】:

      • 如果您使用自动布局,这是正确的答案。我最初担心没有完全约束布局,但它被记录为以这种方式工作,所以它应该是好的。 developer.apple.com/library/ios/documentation/UserExperience/…
      • 为添加缺少的 contrinats 提供错误如何处理?
      • @MyMasterPeice,我已经在 Xcode 8 中重新测试了这个示例,我没有收到任何缺少约束的错误。我添加了一个具有我正在使用的确切约束的图像。试着复制这个确切的例子。你不应该得到任何错误。
      • @Suragch 我没有看到你的演示应用程序,但我在 textview 中尝试了同样的事情,它直接放在内容视图中,在这个解决方案中没有用,但如果我们在 UIView 中包装 textview 那么它只是完美的答案,这是答案中没有提到的棘手点,但这对我有用!
      • @MyMasterPeice,好的,我没有太多使用内容视图,所以我认为它在任何地方都一样。感谢您的答复。我很高兴你能成功。
      【解决方案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]; 它会根据文字自动设置高度或宽度。

      【讨论】:

      • 非常感谢!我喜欢你详细的编码。很有帮助。
      • 非常感谢我的朋友。如果您有任何其他问题,请告诉我。请投票给我的答案
      【解决方案4】:

      您只需计算UILabel 字符串大小的宽度,试试这个简单的代码设置UILabel 大小

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

      【讨论】:

      • 谢谢。我也会听取你的建议。
      【解决方案5】:

      试试这个

              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]
      

      【讨论】:

        【解决方案6】:

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

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

        //可以从expectedLabelSize获取width width height并进行相应设置

        【讨论】:

          【解决方案7】:

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

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

          1. 将 textview 放在 UIView 中,而不是直接放在 content-view 中 在故事板中
          2. 从情节提要禁用文本视图的滚动
          3. 添加前导和顶部约束,因为我已添加到下面的视图中 屏幕截图(尾随约束是可选的,但我已添加)

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

          结果:

          【讨论】:

            【解决方案8】:

            你只需要放两行代码

            lbl1.numberOfLines = 0
                lbl1.sizeToFit()
            

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

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

            【讨论】:

              猜你喜欢
              • 2012-02-06
              • 1970-01-01
              • 2012-03-20
              • 1970-01-01
              • 2015-07-07
              • 2015-09-16
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多