Resolved swift UIColor extension

Discussion in 'iOS Programming' started by erdinc27, Aug 28, 2016.

  1. erdinc27 macrumors regular

    Joined:
    Jul 20, 2011
    #1
    i want to extend UIColor. But when i call the method then i get error. Here how i extend

    Code:
    import Foundation
    import UIKit
    
    extension UIColor {
       
        func theMainColor() -> UIColor {
           
            return UIColor(red: 224, green: 0, blue: 30, alpha: 1.0)
        }
    }
    and how i call it
    Code:
    self.view.backgroundColor = UIColor.theMainColor()
    but here it wants me to enter a parameter.

    Am i doing something wrong ?
     
  2. PhoneyDeveloper macrumors 68040

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    It needs to be a class method. Look at the UIColor header.
     
  3. erdinc27 thread starter macrumors regular

    Joined:
    Jul 20, 2011
    #3
    That was the answer. Thank you buddy.
     
  4. PhoneyDeveloper macrumors 68040

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #4
    Few other comments. There are a number of UIColor extensions on github that one might want to use or look at.

    There are some questions I have about the best way to implement these UIColor extensions that I always have in every app. In Objective-C you can have function-scope static variables so the app only ever needs to build a single instance of your UIColor objects. There are no such function-scope statics in swift. In swift you can have file-scope let constants, which gives you a similar kind of constant. In the code shown above the method is building a new UIColor object every time it's called, which maybe isn't a terrible thing but seems slightly wasteful.

    I haven't dug into this very deeply and I wonder what the best way to implement these UIColor extensions is in swift. I'm currently doing it like this

    Code:
    private let mainColor = UIColor(red: 224, green: 0, blue: 30, alpha: 1.0)
    class func theMainColor() -> UIColor {
            return mainColor
    }
    However, if you've got a library of colors and a given app will only ever use a few of them it also seems wasteful to have private let constants for all the colors.

    (There's also a way of having a private struct inside the class in order to have class variables but that seemed too goofy to me.)

    Comments?
     
  5. erdinc27 thread starter macrumors regular

    Joined:
    Jul 20, 2011
    #5
    Actually i have done the same way u shared the code. But if i learn better way then i will share it here for sure.
     

Share This Page