redribben

Saving UIColor

Oct 25th, 2017
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.63 KB | None | 0 0
  1. import UIKit
  2.  
  3. extension UserDefaults {
  4.     func color(forKey defaultName: String) -> UIColor? {
  5.         var color: UIColor?
  6.         if let colorData = data(forKey: defaultName) {
  7.             color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
  8.         }
  9.         return color
  10.     }
  11.    
  12.     func set(_ value: UIColor?, forKey defaultName: String) {
  13.         var colorData: NSData?
  14.         if let color = value {
  15.             colorData = NSKeyedArchiver.archivedData(withRootObject: color) as NSData?
  16.         }
  17.         set(colorData, forKey: defaultName)
  18.     }
  19. }
  20.  
  21. extension UIColor {
  22.     class func paper() -> UIColor {
  23.         return UIColor(red:248/255, green:236/255, blue:194/255, alpha:1.0)
  24.     }
  25. }
  26.  
  27.  
  28. let myObject: UIColor = UIColor.paper()
  29. let objectArray = [UIColor.white, UIColor.lightGray, UIColor.red, UIColor.paper()]
  30.  
  31. print(myObject)
  32. //Prints: UIExtendedSRGBColorSpace 0.972549 0.92549 0.760784 1
  33. print(objectArray)
  34. //Prints: [UIExtendedGrayColorSpace 1 1, UIExtendedGrayColorSpace 0.666667 1, UIExtendedSRGBColorSpace 1 0 0 1, UIExtendedSRGBColorSpace 0.972549 0.92549 0.760784 1]
  35.  
  36. let indx : Int = objectArray.index(where: { $0 == myObject })!
  37. print(indx)
  38. //Prints: 3
  39.  
  40. //Saving
  41. UserDefaults.standard.set(myObject, forKey: "myKey")
  42.  
  43. //Extracting
  44. let defaultColor : UIColor = UserDefaults.standard.color(forKey: "myKey")!
  45. print(defaultColor)
  46. //Prints: UIExtendedSRGBColorSpace 0.972549 0.92549 0.760784 1
  47.  
  48. let indexOfSavedColor : Int = objectArray.index(of: defaultColor)!
  49. //Error Message here: fatal error: unexpectedly found nil while unwrapping an Optional value
  50.  
  51. print(indexOfSavedColor)
Advertisement
Add Comment
Please, Sign In to add comment