【问题标题】:Strange behaviour with NSLogNSLog 的奇怪行为
【发布时间】:2011-05-17 05:35:49
【问题描述】:

我正在使用 NSLog 来检查 UITextView。我的代码中有以下日志记录语句:

    NSLog(@"textView: %@",textView);
    NSLog(@"textView.frame: %@",textView.frame);
    NSLog(@"[textView frame]: %@",[textView frame]);

在控制台的输出中,我得到以下信息:

2010-11-29 22:00:38.252 MenuMaker[57602:207] textView: <UITextView: 0x3b3afe0; frame = (0 0; 320 387); text = 'blah...'; clipsToBounds = YES; autoresize = RM+BM; layer = <CALayer: 0x3b3afa0>>
2010-11-29 22:00:38.254 MenuMaker[57602:207] textView.frame: (null)
2010-11-29 22:00:38.254 MenuMaker[57602:207] [textView frame]: (null)

输出的第一行,因为它包含 'frame = (0 0; 320 387)' 位,让我相信 UITextView 的 frame 变量已全部设置。但是为什么在这种情况下接下来的两行显示为 null 呢?他们不应该转储框架的值吗?

提前致谢

【问题讨论】:

  • 这是否与 frame 是一个 cgrect 它是一个结构而不是一个类的事实有关?

标签: ios objective-c cocoa-touch uitextview nslog


【解决方案1】:

UIView.frame 只是一个CGRect 结构(它又包含一个CGPoint 和一个CGSize 结构)。 因此不涉及任何类,并且因为只有类可以具有字符串表示,所以您将显示null。如果你想要框架的值,你必须做的是这样的:

NSLog(@"textView.frame origin: %f %f", textView.frame.origin.x, textView.frame..origin.y);
NSLog(@"textView.frame size: %f %f", textView.frame.size.width, textView.frame.size.height);

【讨论】:

    【解决方案2】:

    文本视图。 frame 将返回一个 CGRect 值。所以如果你想知道一个 textView 的帧值

    NSLog(@"textView frame height: %f",textView.frame.size.height);
    NSLog(@"textView frame width: %f",textView.frame.size.width);
    NSLog(@"textView frame x Position: %f",textView.frame.origin.x);
    NSLog(@"textView frame y Position: %f",textView.frame.origin.y);
    

    当 NSLog 无法识别接收到的对象时,会将该值视为 null。

    【讨论】:

      【解决方案3】:

      你也可以这样做

      NSLog(@"%@",[NSValue valueWithCGRect:textView.frame]);
      

      【讨论】:

        【解决方案4】:

        正如其他人所指出的,CGRect 只是一个结构,因此缺少 -description 方法(这是 NSLog 使用的 NSString 的 +stringWithFormat 静态方法在格式字符串中替换 %@ 的方法)。因此,您不能直接将其传递给 NSLog。

        但是,无需像建议的那样单独输出任何值。 Cocoa 提供了许多内置方法,可以将多个 Core Graphics 结构呈现为字符串:

        NSStringFromCGRect()
        NSStringFromCGPoint()
        NSStringFromCGSize()
        NSStringFromCGAffineTransform()
        

        等等。因此,以字符串的形式输出 CGRect 变得超级简单:

        NSLog(@"%@", NSStringFromCGRect(rect));
        

        您可以在“字符串转换”下找到所有这些帮助方法here

        【讨论】:

          【解决方案5】:

          在 Swift 中很简单:

          println("\(textView.frame)")
          

          【讨论】:

          • 问题是关于 Objective-C,而不是 Swift。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-08
          相关资源
          最近更新 更多