Connecting the Slider to the View Controller

Hi together,

I just started yesterday with the IOS apprentice book. Unfortunately I got stuck adding the @IBAction func slider moved command to my Bulls Eye App. I wrote the code just as I am supposed to do but I get an error message and cant compile my app any longer. The error says " Only instance methods can be declared @IBAction".

And if I want to ctrl drag the slider to the View controller the slider moved action does not appear in the drop down menu.

As I am a total programming beginner I need some help here as I am really stuck by now.

Thank you in advance.

It sounds like you put the @IBAction func ... outside the last }. It must be inside the { and } for class ViewController. That should fix it. :smile:

1 Like

Thanks for your answer. Could you have a short look over my code? Maybe that specifies the problem:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func showAlert () {
    let alert = UIAlertController (title: "Hello World", message: "this is my first app!", preferredStyle: .alert)
    
    let action = UIAlertAction (title: "Awesome", style: .default, handler:nil)
    
    alert.addAction(action)
    
    present(alert, animated:true,completion: nil)
    
    @IBAction func sliderMoved(_ slider: UISlider) {
        print("The value of the slider is now: \(slider.value)")
    }
}

}

Well you have one IBAction func inside another - I think all your IBAction funcs must be declared in class scope. (That makes them “instance methods”)

1 Like

Hi, thanks for your answer.

So that would mean maybe if I seperate them by a closing } this would fix the problem?

like this:

@IBAction func showAlert () {
    let alert = UIAlertController (title: "Hello World", message: "this is my first app!", preferredStyle: .alert)
    
    let action = UIAlertAction (title: "Awesome", style: .default, handler:nil)
    
    alert.addAction(action)
    
    present(alert, animated:true,completion: nil) 
 }

 @IBAction func sliderMoved(_ slider: UISlider) {
        print("The value of the slider is now: \(slider.value)")
 }

Thank you for your help guys I solved it !