Swift : String + 查找子串的ranges, string转Color

资料:
Scanner
查找子串的ranges


extension String{
    //十六进制字符串转换成 UIColor hex
    func transferStringToColor(alpha:CGFloat? = 1) -> UIColor {
        
        var color = UIColor.red
        var cStr : String = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
        
        if cStr.hasPrefix("#") {
            let index = cStr.index(after: cStr.startIndex)
            cStr = cStr.substring(from: index)
        }
        if cStr.count != 6 {
            return UIColor.black
        }
        
        let rRange = cStr.startIndex ..< cStr.index(cStr.startIndex, offsetBy: 2)
        let rStr = cStr.substring(with: rRange)
        
        let gRange = cStr.index(cStr.startIndex, offsetBy: 2) ..< cStr.index(cStr.startIndex, offsetBy: 4)
        let gStr = cStr.substring(with: gRange)
        
        let bIndex = cStr.index(cStr.endIndex, offsetBy: -2)
        let bStr = cStr.substring(from: bIndex)
        
        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        Scanner(string: rStr).scanHexInt32(&r)
        Scanner(string: gStr).scanHexInt32(&g)
        Scanner(string: bStr).scanHexInt32(&b)
        
        color = UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha!)
        return color
    }
    
    /// 从字符串中提取数字
    func getIntFromString() -> String {
        let scanner = Scanner(string: self)
        scanner.scanUpToCharacters(from: CharacterSet.decimalDigits, into: nil)
        var number :Int = 0
        scanner.scanInt(&number)
        return String(number)
        
    }
    
    /// 查找子字符串
    func ranges(of string: String) -> (range:[Range], nsRnage: [NSRange]) {
        var rangeArray = [Range]()
        var nsRangeArray = [NSRange]()
        var searchedRange: Range
        guard let sr = self.range(of: self) else {
            return (rangeArray, nsRangeArray)
        }
        searchedRange = sr
        var resultRange = self.range(of: string, options: .regularExpression, range: searchedRange, locale: nil)
        while let range = resultRange {
            rangeArray.append(range)
            nsRangeArray.append(NSRange(range,in:self))
            searchedRange = Range(uncheckedBounds: (range.upperBound, searchedRange.upperBound))
            resultRange = self.range(of: string, options: .regularExpression, range: searchedRange, locale: nil)
        }
        return (rangeArray,nsRangeArray)
    }

    /// range -> NSRange
    func nsRange(from range: Range) -> NSRange? {
        
        let utf16view = self.utf16
        
        if let from = range.lowerBound.samePosition(in: utf16view), let to = range.upperBound.samePosition(in: utf16view) {
            
            return NSMakeRange(utf16view.distance(from: utf16view.startIndex, to: from), utf16view.distance(from: from, to: to))
            
        }
        return nil
    }
}

你可能感兴趣的:(Swift : String + 查找子串的ranges, string转Color)