2

I have a function:

func handleChange(isShown:Bool){
        if isShown {
           // do something A
        }else{
           // do something B
        }
    }

If I want a UISlider to add the above action with the isShown defaulting to false, and I will call the method handleChange(isShown:Bool) with true in another function. The wrong code as follows:

slider.addTarget(self, action: #selector(handleValue(isShown:false)), for: .valueChanged) 

And I know the right code needs to be:

slider.addTarget(self, action: #selector(handleValue(isShown:)), for: .valueChanged) 

I just want to know how can I set the 'isShown' as false in swift? Appreciate you can reply.

Ringo
  • 1,173
  • 1
  • 12
  • 25
  • 4
    You can't. Either there is no parameter or the parameter must be the `UISlider` instance. The syntax with parameter must be `handleChange(_ sender: UISlider)` – vadian Aug 18 '17 at 15:59
  • You can't. All you can pass is the `sender`, which in this case is a `UISlider`. Your "right code" isn't. –  Aug 18 '17 at 16:01
  • See my edited first comment. – vadian Aug 18 '17 at 16:02
  • @vadian,@dfd,@Jaydeep thanks, and I will go to have a further understanding of 'addTarget' – Ringo Aug 18 '17 at 16:20

1 Answers1

3

One solution is to use a helper function that is separate from the selector function. The selector function can call the helper function, which can have as many parameters as you wish.

Adding the target:

slider.addTarget(self, action: #selector(handleChange(_ sender: UISlider)), for: .valueChanged)

Target function:

func handleChange(sender: UISlider) {
    // logic based on the action or slider
    doSomething(isShown: true)
}

Helper function:

func doSomething(isShown: Bool) {
    // make your changes using the parameters here
}
nathangitter
  • 9,607
  • 3
  • 33
  • 42