【问题标题】:How to calculate UILabel width based on text length?如何根据文本长度计算 UILabel 宽度?
【发布时间】:2011-04-01 10:43:47
【问题描述】:

我想在 UILabel 旁边显示一个图像,但是 UILabel 的文本长度可变,所以我不知道将图像放在哪里。我怎样才能做到这一点?

【问题讨论】:

    标签: ios objective-c swift uikit uilabel


    【解决方案1】:
    CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
                            constrainedToSize:maximumLabelSize 
                            lineBreakMode:yourLabel.lineBreakMode]; 
    

    What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?

    这个问题可能有你的答案,它对我有用。


    对于 2014 年,我在这个新版本中进行了编辑,基于下面 Norbert 的超方便评论!这无所不能。干杯

    // yourLabel is your UILabel.
    
    float widthIs = 
     [self.yourLabel.text
      boundingRectWithSize:self.yourLabel.frame.size                                           
      options:NSStringDrawingUsesLineFragmentOrigin
      attributes:@{ NSFontAttributeName:self.yourLabel.font }
      context:nil]
       .size.width;
    
    NSLog(@"the width of yourLabel is %f", widthIs);
    

    【讨论】:

    • 请注意:自 iOS7 以来已弃用。现在首选的方式是:[yourString boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:yourLabel.font } context:nil];
    • 您也可以使用 IntrinsicContentSize 属性。我不太喜欢 Objective-c,但它应该是这样的:self.yourLabel.intrinsicContentSize 这会给你标签内容的大小,所以你可以从那里得到宽度。
    • 只需yourLabel.intrinsicContentSize.width 效果很好,请查看下面的答案。
    【解决方案2】:

    这是我在应用其他 SO 帖子(包括 Aaron 的链接)的一些原则后得出的结论:

    AnnotationPin *myAnnotation = (AnnotationPin *)annotation;
    
    self = [super initWithAnnotation:myAnnotation reuseIdentifier:reuseIdentifier];
    self.backgroundColor = [UIColor greenColor];
    self.frame = CGRectMake(0,0,30,30);
    imageView = [[UIImageView alloc] initWithImage:myAnnotation.THEIMAGE];
    imageView.frame = CGRectMake(3,3,20,20);
    imageView.layer.masksToBounds = NO;
    [self addSubview:imageView];
    [imageView release];
    
    CGSize titleSize = [myAnnotation.THETEXT sizeWithFont:[UIFont systemFontOfSize:12]];
    CGRect newFrame = self.frame;
    newFrame.size.height = titleSize.height + 12;
    newFrame.size.width = titleSize.width + 32;
    self.frame = newFrame;
    self.layer.borderColor = [UIColor colorWithRed:0 green:.3 blue:0 alpha:1.0f].CGColor;
    self.layer.borderWidth = 3.0;
            
    UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(26,5,newFrame.size.width-32,newFrame.size.height-12)];
    infoLabel.text = myAnnotation.title;
    infoLabel.backgroundColor = [UIColor clearColor];
    infoLabel.textColor = [UIColor blackColor];
    infoLabel.textAlignment = UITextAlignmentCenter;
    infoLabel.font = [UIFont systemFontOfSize:12];
    
    [self addSubview:infoLabel];
    [infoLabel release];
    

    在此示例中,我将自定义引脚添加到 MKAnnotation 类,该类根据文本大小调整 UILabel 的大小。它还在视图的左侧添加了一个图像,因此您可以看到一些管理适当间距以处理图像和填充的代码。

    关键是使用CGSize titleSize = [myAnnotation.THETEXT sizeWithFont:[UIFont systemFontOfSize:12]];,然后重新定义视图的尺寸。您可以将此逻辑应用于任何视图。

    虽然 Aaron 的回答对某些人有用,但对我却没有用。这是一个更详细的解释,如果你想要一个带有图像和可调整大小的 UILabel 的更动态的视图,你应该在去其他任何地方之前立即尝试。我已经为你做了所有的工作!!

    【讨论】:

      【解决方案3】:

      所选答案对于 iOS 6 及以下版本是正确的。

      在 iOS 7 中,sizeWithFont:constrainedToSize:lineBreakMode:弃用。现在建议您使用boundingRectWithSize:options:attributes:context:

      CGRect expectedLabelSize = [yourString boundingRectWithSize:sizeOfRect
                                                          options:<NSStringDrawingOptions>
                                                       attributes:@{
                                                          NSFontAttributeName: yourString.font
                                                          AnyOtherAttributes: valuesForAttributes
                                                       }
                                                          context:(NSStringDrawingContext *)];
      

      请注意,返回值是 CGRect 而不是 CGSize。希望这对在 iOS 7 中使用它的人们有所帮助。

      【讨论】:

        【解决方案4】:

        yourLabel.intrinsicContentSize.width 用于 Objective-C / Swift

        【讨论】:

        • 对我不起作用,它不是根据文本计算标签的宽度高度
        • 非常适合我,也可以使用自定义字体!
        • 获取动态标签宽度的完美答案
        【解决方案5】:

        在iOS8 sizeWithFont 已被弃用,请参考

        CGSize yourLabelSize = [yourLabel.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:yourLabel.font size:yourLabel.fontSize]}];
        

        你可以在 sizeWithAttributes 中添加你想要的所有属性。 您可以设置的其他属性:

        - NSForegroundColorAttributeName
        - NSParagraphStyleAttributeName
        - NSBackgroundColorAttributeName
        - NSShadowAttributeName
        

        等等。但可能你不需要其他人

        【讨论】:

          【解决方案6】:

          迅速

           yourLabel.intrinsicContentSize().width 
          

          【讨论】:

          • 这个答案只对已经布局好的视图有效
          • XCode 不喜欢这些括号。
          【解决方案7】:
          CGRect rect = label.frame;
          rect.size = [label.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:label.font.fontName size:label.font.pointSize]}];
          label.frame = rect;
          

          【讨论】:

          • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方发表评论 - 您可以随时评论自己的帖子,一旦您有足够的reputation,您就可以comment on any post
          • 这个答案告诉如何根据文本调整标签大小。这有什么问题?
          【解决方案8】:

          使用约束的 Swift 4 答案

          label.text = "Hello World"
          
          var rect: CGRect = label.frame //get frame of label
          rect.size = (label.text?.size(attributes: [NSFontAttributeName: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
          labelWidth.constant = rect.width // set width to Constraint outlet
          

          使用约束的 Swift 5 答案

          label.text = "Hello World"
          
          var rect: CGRect = label.frame //get frame of label
          rect.size = (label.text?.size(withAttributes: [NSAttributedString.Key.font: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
          labelWidth.constant = rect.width // set width to Constraint outlet
          

          【讨论】:

          • 太棒了!方便根据文本计算 UIButton 的宽度,intrinsicContentSize.width 并不总是正常工作。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-02-23
          • 1970-01-01
          • 2019-03-22
          • 2019-09-20
          • 1970-01-01
          • 2010-10-28
          • 2019-07-27
          相关资源
          最近更新 更多