2015-01-06 29 views
7

我正在用Swift編寫一個命令行工具,而且我在shell中顯示顏色時遇到問題。我使用下面的代碼:使用Swift命令行工具輸出顏色

println("\033[31;32mhey\033[39;39m") 

甚至

NSFileHandle.fileHandleWithStandardOutput().writeData("\033[31;32mhey\033[39;39m".dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!) 

它工作時,我用一個簡單的回聲在PHP(文本顯示爲綠色),但有它不」的理由t在Swift命令行工具中工作?

謝謝!

+0

這裏查出來這個驚人的解決方案:https://stackoverflow.com/questions/9005769/any-way-to-print-in-color-with-nslog – Martian2049

回答

19

Swift內置了Unicode支持。這會使使用反斜槓失效。這樣我就可以用「\ u {}」語法來使用顏色代碼。這是一個在終端上完美工作的println代碼。

// \u{001B}[\(attribute code like bold, dim, normal);\(color code)m 

// Color codes 
// black 30 
// red  31 
// green 32 
// yellow 33 
// blue 34 
// magenta 35 
// cyan 36 
// white 37 

println("\u{001B}[0;33myellow") 

希望它有幫助。

+0

它的工作原理實際上,謝謝! –

+1

我不適用於iOS的swift 1.2編程,我在輸出中看不到顏色 – eliocs

+1

Xcode控制檯不會在您打印顏色時不安裝XcodeColors插件 - > https:// github .com/robbiehanson/XcodeColors – eliocs

17

基於@cyt答案,我寫了一個簡單枚舉這些顏色也重載+操作,因此您可以打印使用該枚舉。

這一切都up on Github,但它就是這麼簡單:

enum ANSIColors: String { 
    case black = "\u{001B}[0;30m" 
    case red = "\u{001B}[0;31m" 
    case green = "\u{001B}[0;32m" 
    case yellow = "\u{001B}[0;33m" 
    case blue = "\u{001B}[0;34m" 
    case magenta = "\u{001B}[0;35m" 
    case cyan = "\u{001B}[0;36m" 
    case white = "\u{001B}[0;37m" 

    func name() -> String { 
     switch self { 
     case black: return "Black" 
     case red: return "Red" 
     case green: return "Green" 
     case yellow: return "Yellow" 
     case blue: return "Blue" 
     case magenta: return "Magenta" 
     case cyan: return "Cyan" 
     case white: return "White" 
     } 
    } 

    static func all() -> [ANSIColors] { 
     return [.black, .red, .green, .yellow, .blue, .magenta, .cyan, .white] 
    } 
} 

func + (let left: ANSIColors, let right: String) -> String { 
    return left.rawValue + right 
} 

// END 


// Demo: 

for c in ANSIColors.all() { 
    println(c + "This is printed in " + c.name()) 
} 
+1

'「\ u {001B} [0; 0m」'重置爲默認顏色。 – devios1

5

你可以用彩虹,如果你不介意使用它作爲一個框架。

import Rainbow 
print("Red text".red) 
print("Yellow background".onYellow) 
print("Light green text on white background".lightGreen.onWhite) 

https://github.com/onevcat/Rainbow