justinmeiners / ios-color-wheel

A fully scalable, dynamically rendered color wheel for iOS.
82 stars 15 forks source link

colorWheelDidChangeColor doesn't work in swift #9

Open simonrieser opened 8 years ago

simonrieser commented 8 years ago

Hello

Coud you please help how to implement the colorWheelDidChangeColor method in swift 2? How do i set the delegate to self? That doesn't work: cw!.delegate = self

I tried it with this code:

var cw: ISColorWheel? cw = ISColorWheel(frame:CGRectMake(size!.width / 2 - wheelSize!.width / 2, size!.height * 0.1, wheelSize!.width, wheelSize!.height)) cw!.continuous = true self.view.addSubview(cw!)

And the action method:

func colorWheelDidChangeColor(colorWheel: ISColorWheel) { view.backgroundColor = colorWheel.currentColor() }

Thank you for your help.

Simon

eshirima commented 8 years ago

Problems

  1. currentColor is a variable and not a method hence you need to use colorWheel.currentColor
  2. You haven't set your ViewController to conform to ISColorWheelDelegate

Solution I created a global variable as so: var colorWheelView: ISColorWheel = ISColorWheel()

Then after specifying its dimensions, I set its delegate; colorWheelView.delegate = self. I'd recommend you do this before colorWheelView.continuous = true

Conform Class Delegation I You can make an extension of your class which implements the ISColorWheelDelegate as such:

extension yourVC: ISColorWheelDelegate
{ 
          func colorWheelDidChangeColor(colorWheel: ISColorWheel!)
          {
                     self.view.backgroundColor = colorWheel.currentColor
          }
}

Conform Class Delegation II Or you could just add the delegate straight onto the VC as shown below:

class yourVC: itsParentController, ISColorWheelDelegate
{
         func colorWheelDidChangeColor(colorWheel: ISColorWheel)
         {
                  view.backgroundColor = colorWheel.currentColor
         }
}

Side Note If you opt the first option to set your delegate, extensions are added outside of the class. Its up to you whether you keep them before or after the class.

Two Cents If you follow the Swift Style Guideline, the first delegation option is favorable because you separate respective 'library' (for luck of a better term) implementations from the core class implementations plus it makes your code more readable. With the second option, you're pretty much just dumping all the code inside and you can imagine how tedious it'll get once you have multiple delegations and datasources to conform to.