0

I need to store color and display color in other viewController. When i'm saving it saving like this UIDynamicSystemColor: 0x600001127620; name = systemBlueColor

With that data how can i display color and it was in string type in realm object.

How can i do that?

CategoryForm :-

import RealmSwift

class CategoryForm : Object {


    @objc dynamic var categoryName : String = ""
    @objc dynamic var categoryColor : String = ""

}

category SaveColor :-

struct CategoryVaraible {

    static  var categoryArray : Results<CategoryForm>? 

}
class CategoryDetailsViewController : UIViewController {

var categories = CategoryVaraible.categoryArray

    var color = [UIColor.secondarySystemFill,UIColor.systemRed,UIColor.systemPink,UIColor.systemOrange,UIColor.systemYellow,UIColor.systemGreen,UIColor.systemBlue,UIColor.systemPurple]

     var colorSelected : UIColor!

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
             let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "ColorViewCell", for: indexPath) as! ColorViewCell
            cell.backgroundColor = color[indexPath.row]


            return cell

           }
        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {


            let item = indexPath.row
            if item == 0 {
                colorSelected = UIColor.secondarySystemFill
            }else if item == 1 {
                colorSelected = UIColor.systemRed
            }else if item == 2 {
                colorSelected = UIColor.systemPink
            }else if item == 3 {
                colorSelected = UIColor.systemOrange
            }else if item == 4 {
                colorSelected = UIColor.systemYellow
            }else if item == 5 {
                colorSelected = UIColor.systemGreen
            }else if item == 6 {
                colorSelected = UIColor.systemBlue
            }else if item == 7 {
                colorSelected = UIColor.systemPurple
            }
          } 
    //Here Saving 
     @IBAction func saveAction(_ sender: UIButton) {
             let newArray = CategoryForm()
     newArray.categoryName = categoryName.text!

           newArray.categoryColor = "\(colorSelected!)"

     self.saveItems(category: newArray)

      self.navigationController?.popViewController(animated: true)

    }

    func saveItems(category: CategoryForm) {
                                       do{

                                           try realm.write {//Save/Create
                                               realm.add(category)
                                           }

                                       }catch {
                                           print("Error in saving \(error)")

                                       }
                                   }

After saving Here to display the saved color

Displaying ViewController :-

 var categories = CategoryVaraible.categoryArray

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return categories?.count ?? 1

           }

           func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
               let cell = self.tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath) as! CategoryCell

            let colorStr = categories?[indexPath.row].categoryColor

<UIDynamicSystemColor: 0x600001127620; name = systemBlueColor>

            cell.circleImage.backgroundColor =   UIImage(name: colorStr as! String)//Here We need to display color
    return cell 
    }

2 Answers2

0

If you don't care about darkmode and system colors, I would add a couple of simple extensions to serialize/deserialize a UIColor to a standard value like ARGB in json or a even better HEX as Int.

Plenty of solutions around, eg: https://stackoverflow.com/a/19072934/691977

And then just store the single String or Int value. When reading have an accessor method that converts the stored value to a UIInt.

Something like:

extension UIColor {
   init(hex: UInt32){
       ...
   }
   var hex: UInt32 {
       ...
   }
}


class CategoryForm : Object {


    @objc dynamic var categoryName : String = ""
    @objc dynamic var categoryColor : UInt32 = 0

    var color: UIColor? {
        get {
            return UIColor(hex: self.categoryColor)
        }
        set {
            self.categoryColor = newValue.hex
        }
    }



}
jalone
  • 1,953
  • 4
  • 27
  • 46
  • How can i use this in saving block and how to retrive that saved color. –  Oct 30 '19 at 04:04
  • Maybe you should read up the 100.342.334.823 questions on "how to use Realm", or formulate your question more carefully. – jalone Oct 30 '19 at 19:26
0

I really like the other answer but here's another option. Save the color components in a list property of the object.

class ColorClass: Object {
    let colorName = ""
    let colorComponents = List<Float>() //this will be an array of [r, g, b, a]
}

Let's save the color Orange to Realm. You could also pass this color as a Realm object, use it as a property of another realm class etc.

let myColor = ColorClass()
let cgOrangeComponents = NSColor.orange.cgColor.components! //use orange for example
let floatOrangeComponents = cgOrangeComponents.map { Float($0) } //Need Floats for Realm
myColor.colorName = "Orange"
myColor.colorComponents.append( floatOrangeComponents[0] )
myColor.colorComponents.append( floatOrangeComponents[1] )
myColor.colorComponents.append( floatOrangeComponents[2] )
myColor.colorComponents.append( floatOrangeComponents[3] )

try! realm.write {
   realm.add(myColor)
}

If you want to read and use the color here's the code.

let colorObject = realm.objects(ColorClass.self).filter("colorName == 'Orange'")
let red = CGFloat( colorObject.colorComponents[0] )
let green = CGFloat( colorObject.colorComponents[1] )
let blue = CGFloat( colorObject.colorComponents[2] )
let alpha = CGFloat( colorObject.colorComponents[3] )

let orange = CGColor.init(red: red, green: green, blue: blue, alpha: alpha)

self.someImage.layer?.backgroundColor = orange

You could of course build more of the logic into the colorClass.

Jay
  • 34,438
  • 18
  • 52
  • 81