-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUIColor+HexString.swift
56 lines (46 loc) · 1.68 KB
/
UIColor+HexString.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
// UIColor+HexString.swift
// Exercises
//
// Created by gz on 2018/2/26.
// Copyright © 2018年 gz. All rights reserved.
//
/*
使用说明:
self.view.backgroundColor = UIColor.init(hexString: "#F8F9FA")
gitHub:https://github.com/865102930/Swift--UIColor-hexString.git
*/
import UIKit
extension UIColor {
convenience init(hexString:String) {
//处理数值
var cString = hexString.uppercased().trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let length = (cString as NSString).length
//错误处理
if (length < 6 || length > 7 || (!cString.hasPrefix("#") && length == 7)){
//返回whiteColor
self.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
return
}
if cString.hasPrefix("#"){
cString = (cString as NSString).substring(from: 1)
}
//字符chuan截取
var range = NSRange()
range.location = 0
range.length = 2
let rString = (cString as NSString).substring(with: range)
range.location = 2
let gString = (cString as NSString).substring(with: range)
range.location = 4
let bString = (cString as NSString).substring(with: range)
//存储转换后的数值
var r:UInt32 = 0,g:UInt32 = 0,b:UInt32 = 0
//进行转换
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
//根据颜色值创建UIColor
self.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1.0)
}
}