ios 有什么办法可以用 NSLog 进行彩色打印?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9005769/
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 16:29:32  来源:igfitidea点击:

Any way to print in color with NSLog?

ioscolorsnslog

提问by Lena Schimmel

In a typical color terminal, there are escape sequences that one can use to print text in different colors. Typically there are 8 colors available. I tried using the standard, ANSI escape sequences for this in NSLog, but no dice. It does not support by that mechanism.

在典型的彩色终端中,可以使用转义序列以不同颜色打印文本。通常有 8 种颜色可供选择。我尝试在 NSLog 中使用标准的 ANSI 转义序列,但没有骰子。它不支持该机制。

Is there a different way to print to the console (log) in color using NSLog?

是否有不同的方式使用 NSLog 以彩色打印到控制台(日志)?

Thanks.

谢谢。

回答by Lena Schimmel

You can use Apple Color Emojito add some color to your Log output like this:

您可以使用Apple Color Emoji为您的日志输出添加一些颜色,如下所示:

if ([self isKindOfClass:[UITableViewController class]])
    NSLog(@" Table View controller Will appear: %@", NSStringFromClass([self class]));
else  if ([self isKindOfClass:[UINavigationController class]])
    NSLog(@" Navigation controller Will appear: %@", NSStringFromClass([self class]));
else
    NSLog(@" View controller Will appear: %@", NSStringFromClass([self class]));

Because the above code might by displayed incorrectly on non-OS-X-platforms, I attached a screenshot of XCode, showing the code and log output:

因为上面的代码可能在非 OS-X 平台上显示不正确,我附上了 XCode 的截图,显示了代码和日志输出:

Screenshot from X Code with Apple Color Emoji in code and log output

Screenshot from X Code with Apple Color Emoji in code and log output

回答by ayoy

A line like this works for me:

像这样的一行对我有用:

NSLog(@"\e[1;31mRed text here\e[m normal text here");

(More colors available here)

这里有更多颜色可用)

Note that you have to actually watch your output in regular console, as Xcode debugging console doesn't seem to support coloring.

请注意,您必须在常规控制台中实际查看输出,因为 Xcode 调试控制台似乎不支持着色。

回答by djromero

You can colorize your NSLogoutput using this Xcode plugin: https://github.com/DeepIT/XcodeColors

您可以NSLog使用此 Xcode 插件为您的输出着色:https: //github.com/DeepIT/XcodeColors

I wrote a few lines with my quick setup instructions and simple custom macros.

我用我的快速设置说明和简单的自定义宏写了几行。

Update: I'm using now NSLoggerwith color support. Much powerful.

更新:我现在使用带有颜色支持的NSLogger。很强大。

回答by Besi

Ayoy's approach seems to work in general in a command line based app with printf:

Ayoy 的方法似乎在基于命令行的应用程序中通常可以使用printf

However, I don't think this works with the built-in Xcode console:

但是,我认为这不适用于内置的 Xcode 控制台:

This:

这个:

NSLog(@"\e[1;31mRed text here\e[m normal text here");

... results in this:

... 结果如下: