Skip to content

Commit 1e82ad3

Browse files
committed
当UIColor遇上Swift
1 parent 0881b92 commit 1e82ad3

14 files changed

Lines changed: 1002 additions & 0 deletions

File tree

KtColor/KTColor.xcodeproj/project.pbxproj

Lines changed: 515 additions & 0 deletions
Large diffs are not rendered by default.

KtColor/KTColor/AppDelegate.swift

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
//
2+
// AppDelegate.swift
3+
// KTColor
4+
//
5+
// Created by 张星宇 on 16/2/14.
6+
// Copyright © 2016年 zxy. All rights reserved.
7+
//
8+
9+
import UIKit
10+
11+
@UIApplicationMain
12+
class AppDelegate: UIResponder, UIApplicationDelegate {
13+
14+
var window: UIWindow?
15+
16+
17+
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
18+
// Override point for customization after application launch.
19+
return true
20+
}
21+
22+
func applicationWillResignActive(application: UIApplication) {
23+
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
24+
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
25+
}
26+
27+
func applicationDidEnterBackground(application: UIApplication) {
28+
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
29+
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
30+
}
31+
32+
func applicationWillEnterForeground(application: UIApplication) {
33+
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
34+
}
35+
36+
func applicationDidBecomeActive(application: UIApplication) {
37+
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
38+
}
39+
40+
func applicationWillTerminate(application: UIApplication) {
41+
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
42+
}
43+
44+
45+
}
46+
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
{
2+
"images" : [
3+
{
4+
"idiom" : "iphone",
5+
"size" : "29x29",
6+
"scale" : "2x"
7+
},
8+
{
9+
"idiom" : "iphone",
10+
"size" : "29x29",
11+
"scale" : "3x"
12+
},
13+
{
14+
"idiom" : "iphone",
15+
"size" : "40x40",
16+
"scale" : "2x"
17+
},
18+
{
19+
"idiom" : "iphone",
20+
"size" : "40x40",
21+
"scale" : "3x"
22+
},
23+
{
24+
"idiom" : "iphone",
25+
"size" : "60x60",
26+
"scale" : "2x"
27+
},
28+
{
29+
"idiom" : "iphone",
30+
"size" : "60x60",
31+
"scale" : "3x"
32+
}
33+
],
34+
"info" : {
35+
"version" : 1,
36+
"author" : "xcode"
37+
}
38+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2+
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="8150" systemVersion="15A204g" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">
3+
<dependencies>
4+
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="8122"/>
5+
</dependencies>
6+
<scenes>
7+
<!--View Controller-->
8+
<scene sceneID="EHf-IW-A2E">
9+
<objects>
10+
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
11+
<layoutGuides>
12+
<viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/>
13+
<viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>
14+
</layoutGuides>
15+
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
16+
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
17+
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
18+
<animations/>
19+
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
20+
</view>
21+
</viewController>
22+
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
23+
</objects>
24+
<point key="canvasLocation" x="53" y="375"/>
25+
</scene>
26+
</scenes>
27+
</document>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2+
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="6211" systemVersion="14A298i" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
3+
<dependencies>
4+
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6204"/>
5+
</dependencies>
6+
<scenes>
7+
<!--View Controller-->
8+
<scene sceneID="tne-QT-ifu">
9+
<objects>
10+
<viewController id="BYZ-38-t0r" customClass="ViewController" customModuleProvider="target" sceneMemberID="viewController">
11+
<layoutGuides>
12+
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
13+
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
14+
</layoutGuides>
15+
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
16+
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
17+
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
18+
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
19+
</view>
20+
</viewController>
21+
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
22+
</objects>
23+
</scene>
24+
</scenes>
25+
</document>

KtColor/KTColor/Info.plist

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+
<plist version="1.0">
4+
<dict>
5+
<key>CFBundleDevelopmentRegion</key>
6+
<string>en</string>
7+
<key>CFBundleExecutable</key>
8+
<string>$(EXECUTABLE_NAME)</string>
9+
<key>CFBundleIdentifier</key>
10+
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
11+
<key>CFBundleInfoDictionaryVersion</key>
12+
<string>6.0</string>
13+
<key>CFBundleName</key>
14+
<string>$(PRODUCT_NAME)</string>
15+
<key>CFBundlePackageType</key>
16+
<string>APPL</string>
17+
<key>CFBundleShortVersionString</key>
18+
<string>1.0</string>
19+
<key>CFBundleSignature</key>
20+
<string>????</string>
21+
<key>CFBundleVersion</key>
22+
<string>1</string>
23+
<key>LSRequiresIPhoneOS</key>
24+
<true/>
25+
<key>UILaunchStoryboardName</key>
26+
<string>LaunchScreen</string>
27+
<key>UIMainStoryboardFile</key>
28+
<string>Main</string>
29+
<key>UIRequiredDeviceCapabilities</key>
30+
<array>
31+
<string>armv7</string>
32+
</array>
33+
<key>UISupportedInterfaceOrientations</key>
34+
<array>
35+
<string>UIInterfaceOrientationPortrait</string>
36+
<string>UIInterfaceOrientationLandscapeLeft</string>
37+
<string>UIInterfaceOrientationLandscapeRight</string>
38+
</array>
39+
</dict>
40+
</plist>

KtColor/KTColor/KtColor.swift

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
//
2+
// KtColor.swift
3+
// KTColor
4+
//
5+
// Created by 张星宇 on 16/2/18.
6+
// Copyright © 2016年 zxy. All rights reserved.
7+
//
8+
9+
import Foundation
10+
import UIKit
11+
12+
// MARK: - 为字符串提供计算属性:ktcolor,根据字符串创建UIColor对象
13+
extension String {
14+
func split(seperator: Character) -> Array<String> {
15+
return characters.split{ $0 == seperator}.map { String($0) }
16+
}
17+
18+
func split(seperator: String) -> Array<String> {
19+
return characters.split(seperator.characters).map { String($0) }
20+
}
21+
22+
public var ktcolor: UIColor {
23+
return ColorParser.colorFromString(self)
24+
}
25+
}
26+
27+
extension CollectionType where Generator.Element: Equatable {
28+
func split<S: SequenceType where Generator.Element == S.Generator.Element>
29+
(seperators: S) -> [SubSequence] {
30+
return split { seperators.contains($0) }
31+
}
32+
}
33+
34+
/**
35+
* 负责字符串处理的内部结构体
36+
*/
37+
private struct ColorParser {
38+
/**
39+
* 从16进制(字母大写)转换成十进制
40+
*
41+
* @return 十进制整数
42+
*/
43+
private static func intFromHex(var hex: String) -> Int {
44+
var sum = 0
45+
hex = hex.uppercaseString
46+
for scalar in hex.unicodeScalars {
47+
let asciiValue = Int(scalar.value)
48+
let n: Int = asciiValue >= 65 ? asciiValue - 55 : asciiValue - 48
49+
sum = sum * 16 + n
50+
}
51+
return sum
52+
}
53+
54+
/**
55+
将字符串数组转换为UIColor对象
56+
57+
:param: colors 数组格式为["12", "34", "56", ("1")],第四个元素如果缺失,默认为1
58+
59+
:returns: UIColor颜色对象
60+
*/
61+
private static func colorFromStringImpl(colors: Array<String>) -> UIColor {
62+
let nums = colors.flatMap{ Int($0) }
63+
let alpha = colors.count == 4 ? CGFloat(Double(colors[3]) ?? 1) : 1
64+
let floats = nums.map{ CGFloat($0) }
65+
66+
return UIColor(red: floats[0]/255.0, green: floats[1]/255.0, blue: floats[2]/255.0, alpha: alpha)
67+
}
68+
69+
/**
70+
根据字符串字面量创建UIColor对象
71+
72+
:param: colorLiteral 字符串字面量,可以是十六进制数字:"#DC143C"、"#ff69b4",不区分大小写
73+
可以是数组形式,如"111 222 223"、"111,222,223,1"、"111, 222, 223, 0.5",支持多种分隔符,默认alpha为1
74+
可以是颜色的英文名称,如"Orchid"、"Purple"、"LightPink"、"DarkSeaGreen"等
75+
完整列表可以参考:http://www.w3school.com.cn/cssref/css_colorsfull.asp
76+
:returns: UIColor对象,如果格式不支持,则返回默认颜色:白色
77+
*/
78+
static func colorFromString(var colorLiteral: String) -> UIColor {
79+
if let hexString = colorHexDictionary[colorLiteral] {
80+
colorLiteral = hexString
81+
}
82+
if colorLiteral.characters.startsWith(["#"]) {
83+
var red, green, blue: Int
84+
red = intFromHex(String(colorLiteral.characters.dropFirst().prefix(2)))
85+
green = intFromHex(String(colorLiteral.characters.dropFirst(3).prefix(2)))
86+
blue = intFromHex(String(colorLiteral.characters.dropFirst(5).prefix(2)))
87+
return UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1)
88+
}
89+
else {
90+
let numsInString1 = colorLiteral.split(", ")
91+
if numsInString1.count == 3 || numsInString1.count == 4 { return colorFromStringImpl(numsInString1) }
92+
93+
let numsInString2 = colorLiteral.split(",")
94+
if numsInString2.count == 3 || numsInString2.count == 4 { return colorFromStringImpl(numsInString2) }
95+
96+
let numsInString3 = colorLiteral.split(" ")
97+
if numsInString3.count == 3 || numsInString3.count == 4 { return colorFromStringImpl(numsInString3) }
98+
else { return UIColor.whiteColor() }
99+
}
100+
}
101+
102+
private static let colorHexDictionary: [String: String] = [
103+
"LightPink": "#FFB6C1", "Pink": "#FFC0CB", "Crimson": "#DC143C", "LavenderBlush": "#FFF0F5",
104+
"PaleVioletRed": "#DB7093", "HotPink": "#FF69B4","DeepPink": "#FF1493", "MediumVioletRed": "#C71585",
105+
"Orchid": "#DA70D6", "Thistle": "#D8BFD8", "plum": "#DDA0DD", "Violet": "#EE82EE", "Magenta": "#FF00FF",
106+
"Fuchsia": "#FF00FF", "DarkMagenta": "#8B008B", "Purple": "#800080", "MediumOrchid": "#BA55D3",
107+
"DarkVoilet": "#9400D3", "DarkOrchid": "#9932CC", "Indigo": "#4B0082", "BlueViolet": "#8A2BE2",
108+
"MediumPurple": "#9370DB", "MediumSlateBlue": "#7B68EE", "SlateBlue": "#6A5ACD", "DarkSlateBlue": "#483D8B",
109+
"Lavender": "#E6E6FA", "GhostWhite": "#F8F8FF", "Blue": "#0000FF", "MediumBlue": "#0000CD", "MidnightBlue": "#191970",
110+
"DarkBlue": "#00008B", "Navy": "#000080", "RoyalBlue": "#4169E1", "CornflowerBlue": "#6495ED",
111+
"LightSteelBlue": "#B0C4DE", "LightSlateGray": "#778899", "SlateGray": "#708090", "DoderBlue": "#1E90FF",
112+
"AliceBlue": "#F0F8FF", "SteelBlue": "#4682B4", "LightSkyBlue": "#87CEFA", "SkyBlue": "#87CEEB",
113+
"DeepSkyBlue": "#00BFFF", "LightBLue": "#ADD8E6", "PowDerBlue": "#B0E0E6", "CadetBlue": "#5F9EA0","Azure": "#F0FFFF",
114+
"LightCyan": "#E1FFFF", "PaleTurquoise": "#AFEEEE", "Cyan": "#00FFFF", "Aqua": "#00FFFF", "DarkTurquoise": "#00CED1",
115+
"DarkSlateGray": "#2F4F4F", "DarkCyan": "#008B8B", "Teal": "#008080", "MediumTurquoise": "#48D1CC",
116+
"LightSeaGreen": "#20B2AA", "Turquoise": "#40E0D0", "Auqamarin": "#7FFFAA", "MediumAquamarine": "00FA9A#",
117+
"MediumSpringGreen": "#F5FFFA", "MintCream": "#00FF7F", "SpringGreen": "#3CB371", "SeaGreen": "#2E8B57",
118+
"Honeydew": "#F0FFF0", "LightGreen": "#90EE90", "PaleGreen": "#98FB98", "DarkSeaGreen": "#8FBC8F", "LimeGreen": "#32CD32",
119+
"Lime": "#00FF00", "ForestGreen": "#228B22", "Green": "#008000", "DarkGreen": "#006400", "Chartreuse": "#7FFF00",
120+
"LawnGreen": "#7CFC00", "GreenYellow": "#ADFF2F", "OliveDrab": "#556B2F", "Beige": "#6B8E23",
121+
"LightGoldenrodYellow": "#FAFAD2", "Ivory": "#FFFFF0", "LightYellow": "#FFFFE0", "Yellow": "#FFFF00", "Olive": "#808000",
122+
"DarkKhaki": "#BDB76B", "LemonChiffon": "#FFFACD", "PaleGodenrod": "#EEE8AA", "Khaki": "#F0E68C", "Gold": "#FFD700",
123+
"Cornislk": "#FFF8DC", "GoldEnrod": "#DAA520", "FloralWhite": "#FFFAF0", "OldLace": "#FDF5E6", "Wheat": "#F5DEB3",
124+
"Moccasin": "#FFE4B5", "Orange": "#FFA500", "PapayaWhip": "#FFEFD5", "BlanchedAlmond": "#FFEBCD",
125+
"NavajoWhite": "#FFDEAD", "AntiqueWhite": "#FAEBD7", "Tan": "#D2B48C", "BrulyWood": "#DEB887", "Bisque": "#FFE4C4",
126+
"DarkOrange": "#FF8C00", "Linen": "#FAF0E6", "Peru": "#CD853F", "PeachPuff": "#FFDAB9", "SandyBrown": "#F4A460",
127+
"Chocolate": "#D2691E", "SaddleBrown": "#8B4513", "SeaShell": "#FFF5EE", "Sienna": "#A0522D", "LightSalmon": "#FFA07A",
128+
"Coral": "#FF7F50", "OrangeRed": "#FF4500", "DarkSalmon": "#E9967A", "Tomato": "#FF6347", "MistyRose": "#FFE4E1",
129+
"Salmon": "#FA8072", "Snow": "#FFFAFA", "LightCoral": "#F08080", "RosyBrown": "#BC8F8F", "IndianRed": "#CD5C5C",
130+
"Red": "#FF0000", "Brown": "#A52A2A", "FireBrick": "#B22222", "DarkRed": "#8B0000", "Maroon": "#800000",
131+
"White": "#FFFFFF", "WhiteSmoke": "#F5F5F5", "Gainsboro": "#DCDCDC", "LightGrey": "#D3D3D3", "Silver": "#C0C0C0",
132+
"DarkGray": "#A9A9A9", "Gray": "#808080", "DimGray": "#696969", "Black": "#000000"
133+
]
134+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
//
2+
// ViewController.swift
3+
// KTColor
4+
//
5+
// Created by 张星宇 on 16/2/14.
6+
// Copyright © 2016年 zxy. All rights reserved.
7+
//
8+
9+
import UIKit
10+
11+
/// 通过继承实现字符串字面量创建UIColor对象
12+
class KtColor: UIColor, StringLiteralConvertible {
13+
required init(stringLiteral value: String) {
14+
super.init(red: 0.5, green: 0.8, blue: 0.25, alpha: 1)
15+
}
16+
17+
required convenience init(extendedGraphemeClusterLiteral value: String) {
18+
self.init(stringLiteral: value)
19+
}
20+
21+
required convenience init(unicodeScalarLiteral value: String) {
22+
self.init(stringLiteral: value)
23+
}
24+
25+
required init?(coder aDecoder: NSCoder) {
26+
fatalError("init(coder:) has not been implemented")
27+
}
28+
29+
required convenience init(colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float) {
30+
self.init(colorLiteralRed: red, green: green, blue: blue, alpha: alpha)
31+
}
32+
}
33+
34+
35+
36+
class ViewController: UIViewController {
37+
38+
override func viewDidLoad() {
39+
super.viewDidLoad()
40+
41+
self.view.backgroundColor = "224, 222, 255, 0.5".ktcolor
42+
self.view.backgroundColor = "#DC143C".ktcolor
43+
self.view.backgroundColor = "SkyBlue".ktcolor
44+
self.view.backgroundColor = "224,222,255".ktcolor
45+
self.view.backgroundColor = "224, 222, 255" as KtColor
46+
}
47+
48+
override func didReceiveMemoryWarning() {
49+
super.didReceiveMemoryWarning()
50+
// Dispose of any resources that can be recreated.
51+
}
52+
}
53+

KtColor/KTColorTests/Info.plist

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+
<plist version="1.0">
4+
<dict>
5+
<key>CFBundleDevelopmentRegion</key>
6+
<string>en</string>
7+
<key>CFBundleExecutable</key>
8+
<string>$(EXECUTABLE_NAME)</string>
9+
<key>CFBundleIdentifier</key>
10+
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
11+
<key>CFBundleInfoDictionaryVersion</key>
12+
<string>6.0</string>
13+
<key>CFBundleName</key>
14+
<string>$(PRODUCT_NAME)</string>
15+
<key>CFBundlePackageType</key>
16+
<string>BNDL</string>
17+
<key>CFBundleShortVersionString</key>
18+
<string>1.0</string>
19+
<key>CFBundleSignature</key>
20+
<string>????</string>
21+
<key>CFBundleVersion</key>
22+
<string>1</string>
23+
</dict>
24+
</plist>

0 commit comments

Comments
 (0)