Swift 16 进制颜色字符串转 UIColor

前端之家收集整理的这篇文章主要介绍了Swift 16 进制颜色字符串转 UIColor前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

import Foundation
import UIKit

extension UIColor {

public convenience init?(hexString: String) {
self.init(hexString: hexString,alpha: 1.0)
}

/**
Create non-autoreleased color with in the given hex string and alpha.
- parameter hexString: The hex string,with or without the hash character.
- parameter alpha: The alpha value,a floating value between 0 and 1.
- returns: A color with the given hex string and alpha.
*/
public convenience init?(hexString: String,alpha: Float) {
var hex = hexString

// Check for hash and remove the hash
if hex.hasPrefix("#") {
hex = hex.substringFromIndex(hex.startIndex.advancedBy(1))
}

if (hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)",options: .RegularExpressionSearch) != nil) {

// Deal with 3 character Hex strings
if hex.characters.count == 3 {
let redHex = hex.substringToIndex(hex.startIndex.advancedBy(1))
let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(1),end: hex.startIndex.advancedBy(2)))
let blueHex = hex.substringFromIndex(hex.startIndex.advancedBy(2))

hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
}

let redHex = hex.substringToIndex(hex.startIndex.advancedBy(2))
let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(2),end: hex.startIndex.advancedBy(4)))
let blueHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(4),end: hex.startIndex.advancedBy(6)))

var redInt: CUnsignedInt = 0
var greenInt: CUnsignedInt = 0
var blueInt: CUnsignedInt = 0

NSScanner(string: redHex).scanHexInt(&redInt)
NSScanner(string: greenHex).scanHexInt(&greenInt)
NSScanner(string: blueHex).scanHexInt(&blueInt)

self.init(red: CGFloat(redInt) / 255.0,green: CGFloat(greenInt) / 255.0,blue: CGFloat(blueInt) / 255.0,alpha: CGFloat(alpha))
}
else {
// Note:
// The swift 1.1 compiler is currently unable to destroy partially initialized classes in all cases,
// so it disallows formation of a situation where it would have to. We consider this a bug to be fixed
// in future releases,not a feature. -- Apple Forum
self.init()
return nil
}
}
}


https://github.com/thii/SwiftHEXColors/blob/master/Sources/SwiftHEXColors.swift

原文链接:https://www.f2er.com/swift/324670.html

猜你在找的Swift相关文章