Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'scanHexInt32' was deprecated in iOS 13.0

What is alternate of scanHexInt32 in iOS 13 (Swift 5+)?

extension UIColor {


    //--------------------------------------------
    class func hexColor(hex:String) -> UIColor {
        var cString:String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()

        if (cString.hasPrefix("#")) {
            cString = String(cString[cString.index(cString.startIndex, offsetBy: 1)...])
        }

        if (cString.count != 6) {
            return UIColor.gray
        }

        var rgbValue:UInt32 = 0

// warning in this line - 'scanHexInt32' was deprecated in iOS 13.0
        Scanner(string: cString).scanHexInt32(&rgbValue)

        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
}

Ref: Snapshot

enter image description here

like image 794
Krunal Avatar asked Sep 10 '19 12:09

Krunal


Video Answer


3 Answers

Update to use UInt64 and scanHexInt64:

convenience init(hex: String, alpha: CGFloat = 1.0) {
    var hexFormatted: String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()

    if hexFormatted.hasPrefix("#") {
        hexFormatted = String(hexFormatted.dropFirst())
    }

    assert(hexFormatted.count == 6, "Invalid hex code used.")

    var rgbValue: UInt64 = 0
    Scanner(string: hexFormatted).scanHexInt64(&rgbValue)

    self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
              green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
              blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
              alpha: alpha)
}
like image 72
Daniel Storm Avatar answered Oct 19 '22 15:10

Daniel Storm


Looks like apple is phasing out Int32 from their 64bit OSs. Try convert your code to use Int64 instead.

@available(iOS, introduced: 2.0, deprecated: 13.0)
open func scanHexInt32(_ result: UnsafeMutablePointer<UInt32>?) -> Bool // Optionally prefixed with "0x" or "0X"


@available(iOS 2.0, *)
open func scanHexInt64(_ result: UnsafeMutablePointer<UInt64>?) -> Bool // Optionally prefixed with "0x" or "0X"
like image 13
John Zhou Avatar answered Oct 19 '22 13:10

John Zhou


There is another Instance Method available

scanInt32(representation:)

Declaration:

func scanInt32(representation: Scanner.NumberRepresentation = .decimal) -> Int32?

Here you have to pass enum .hexadecimal.

I hope it will return same result. Result will be optional.

like image 7
Ashish Kakkad Avatar answered Oct 19 '22 15:10

Ashish Kakkad