ttvcysx
ttvcysx

Reputation: 9

Different functions for one bar button item

I have a view controller with a segmented control(only two segments: Songs and Playlists) and a bar button item. When the songs segment is selected, I want the bar button item to perform action1, and when the playlists segment is selected, I want the bar button item to perform action2. In an attempt to do this I created this function which I declared in the viewDidLoad and in the viewDidAppear:

 func settearButton() {
    let indice = segmentFiltroMusica.selectedSegmentIndex
    switch indice {
    case 0: //Canciones
        btnAgregarMusica.action = #selector(irAAgregarCancionesVC)
        btnAgregarMusica.target = self
    case 1: // Playlists
        btnAgregarMusica.action = #selector(irAAgregarPlaylistsVC)
        btnAgregarMusica.target = self
    default: print("")
    }
}

However, the bar button item is only performing action1, no matter what segment is selected. How could I fix this?

Upvotes: 1

Views: 35

Answers (2)

Jelumar
Jelumar

Reputation: 510

First you should put your function in the class and not the viewDidLoad() or viewDidAppear(). You can make it private since you seem to use it only localy.

If you are using storyboards with a ViewController you probably know that you can drag actions and outlets of your segment and button onto your viewController Class.

Here is how I would do this, by using a Boolean value and change this to select between my actions:

private var myChoice: Bool = false

@IBOutlet weak var segment: NSSegmentedControl!

@IBAction func segmentAction(_ sender: Any) {
    let index: Int = self.segment.selectedSegment
    switch index {
    case 0:
        myChoice = true
    case 1:
        myChoice = false
    default:
        fatalError("This segment does not exist!")
    }
}

@IBAction func buttonAction(_ sender: Any) {
    if myChoice {
        // Do case one
    } else {
        // Do case two
    }
}

If you have more elements in the segment to choose from, take an enum instead of the Boolean. I kept your switch which is good if you will add an enum later, else you can just replace the content of the segmentAction() with:

myChoice = self.segment.selectedSegment == 0

Upvotes: 0

AdamPro13
AdamPro13

Reputation: 7400

I don't think you actually want to change the action of the button. Handle the button tap, check the state of your segment control, then call the appropriate method.

func settearButton() {
   let index = segmentFiltroMusica.selectedSegmentIndex
   switch index {
   case 0:
      irAagregarCancionesVC()

   case 1:
      irAggregarPlaylistsVC()

   default:
      break
   }
}

Upvotes: 1

Related Questions