【问题标题】:How to get the width of an NSString?如何获取 NSString 的宽度?
【发布时间】:2011-03-26 16:08:50
【问题描述】:

我正在尝试获取 NSString 的宽度(例如 NSString *myString = @"hello")。有没有办法做到这一点?

谢谢。

【问题讨论】:

  • 不,因为这个问题是关于 Cocoa Touch 的,而这个问题是关于 Cocoa 的。
  • @Peter Hosey 出色的观察力。

标签: objective-c cocoa nsstring


【解决方案1】:

这是一个相对简单的方法。只需使用适当的字体创建一个 NSAttributedString 并询问其大小:

- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
     NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
     return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
 }

【讨论】:

  • 这会泄漏属性字符串。
  • 是的 - 我假设一个垃圾收集环境。
  • 只需在字符串上使用sizeWithAttributes:return [string sizeWithAttributes:attributes].width;
  • 为了获得一个字符串的宽度,它似乎只是通过用字符串初始化 atribString 并询问 size.width 来工作。我认为你不需要给它任何属性。有时您可能不知道字体属性。是的,分配并释放字符串。这对我有用。谢谢
【解决方案2】:
UIFont * font = [UIFont systemFontOfSize:15];

CGSize stringSize = [aString sizeWithFont:font]; 

CGFloat width = stringSize.width;

【讨论】:

  • sizeWithFont 现在已弃用。它现在应该看起来像 CGSize stringSize = [aString sizeWithAttributes:@{NSFontAttributeName:font}];
【解决方案3】:

使用 UILabel 的属性字符串:

- (CGSize)getStringSizeWithText:(NSString *)string font:(UIFont *)font{

    UILabel *label = [[UILabel alloc] init];
    label.text = string;
    label.font = font;

    return label.attributedText.size;
}

【讨论】:

    【解决方案4】:

    向字符串发送sizeWithAttributes: 消息,传递包含您要用来测量字符串的属性的字典。

    【讨论】:

      【解决方案5】:

      我不知道你是否打算在可可触摸中使用它。如果是,那么:

      - (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
           NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
           return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
       }
      

      不会工作。

      在 cocoa touch 中,您必须添加 coretext 框架并导入标题 并像这样编写代码:

      UIFont *font = [UIFont fontWithName:@"HelveticaNeue-BoldItalic" size:DEFAULT_FONT_SIZE];
      //    NSLog(@"%@", NSFontAttributeName);
      NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, (NSString     *)kCTFontAttributeName, nil];
      

      但是,天啊!!!!!!

      NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithString:self.caption attributes:attributes];
      [as size].width;
      

      NSMutableAttributedString 中没有这个方法的大小!

      终于可以了

      [self.caption sizeWithFont:font].width
      

      【讨论】:

      • 这是我很久以来看到的最令人困惑的答案。你能发布一个完整的sn-p吗?
      【解决方案6】:

      对于 ios 7 及更高版本,这是正确的方法:

      NSString * buttonTitle = @"demo title";
      CGSize stringSize = [buttonTitle sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];
      

      【讨论】:

        【解决方案7】:

        这适用于 iOS 14.5

        Objective-C

        定义属性:

         NSDictionary *attributes = @{
                    NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:25],
                    NSStrokeWidthAttributeName: @(0),
                    NSStrokeColorAttributeName: [UIColor blackColor]
            };
        

        获取宽度和高度:

        - (CGFloat)widthOfString:(NSString *)string {
            CGSize stringSize = [string sizeWithAttributes:attributes];
            return stringSize.width;
        }
        
        - (CGFloat)heightOfString:(NSString *)string {
            CGSize stringSize = [string sizeWithAttributes:attributes];
            return stringSize.height;
        }
        
        

        【讨论】:

          【解决方案8】:

          抱歉,我的问题不够详细,也不是我想要做的。我正在使用文本存储、布局管理器和文本容器。解决方案是使用布局管理器来确定包围矩形的矩形。这是代码。

          NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:@"hello"];
          NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
          NSTextContainer *textContainer = [[NSTextContainer alloc] init];
          
          [layoutManager addTextContainer:textContainer];
          [textContainer release];
          
          [textStorage addLayoutManager:layoutManager];
          [layoutManager release];
          
          //Figure out the bounding rectangle
          NSRect stringRect = [layoutManager boundingRectForGlyphRange:NSMakeRange(0, [layoutManager numberOfGlyphs]) inTextContainer:textContainer];
          

          【讨论】:

          • 这是很长的路要走。如果你通常有一个文本存储、布局管理器和文本容器(并且有一个文本视图计数),那很好,但是有几个更短的方法。
          • 不会分配给NSTextField所需的字符串,然后调用sizeToFit方法->然后从NSTextField检索宽度会更好吗? (我有同样的问题只是想正确地做到这一点)
          【解决方案9】:

          UIKit 对 NSString 有一个很好的补充,让 sizeWithAttributes: 更轻了一点:

          CGSize titleSize = [title sizeWithFont:titleFont 
                               constrainedToSize:contentCellSize 
                                   lineBreakMode:UILineBreakModeWordWrap];
          

          【讨论】:

          • sizeWithFont 已弃用。
          【解决方案10】:

          使用 Objective C 桥时,这是 Stephen 在 Clozure Common Lisp 中的解决方案。我在寻找解决方案时遇到了这篇文章,我只是重写了斯蒂芬的版本,对我来说效果很好。其他使用 Clozure 的人可能会觉得这很有帮助:

          (defun string-width (str font)
            (let* ((dict (#/dictionaryWithObjectsAndKeys: ns:ns-mutable-dictionary
                          font #$NSFontAttributeName
                          ccl:+null-ptr+))
                   (attr (#/initWithString:attributes: (#/alloc ns:ns-attributed-string)
                          (ccl::%make-nsstring str)
                          dict))
                   (size (#/size attr)))
              (ns:ns-size-width size)))
          

          【讨论】:

            【解决方案11】:

            这会奏效。你可以试试看。

            NSDictionary *attrDict = @{NSFontAttributeName : [GenericUtility getOpenSansRegularFontSize:12]};
            CGSize stringBoundingBox = [selectedReservationModel.DateLabel sizeWithAttributes: attrDict];
                lblDeliveryDateWidth = stringBoundingBox.width;
            

            【讨论】:

              【解决方案12】:

              如果您想知道如何检查标签大小,您应该使用 UIFont,而不是 NSFont(甚至不确定是否存在)

              【讨论】:

              • UIFont 适用于 iOS,NSFont 适用于 Mac OS X。
              猜你喜欢
              • 1970-01-01
              • 2011-10-21
              • 2019-02-13
              • 2013-07-27
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-07-12
              • 2014-05-01
              相关资源
              最近更新 更多