Adam Adam - 1 year ago 126
iOS Question

Bar button double action swift

Trying to make my bar button do 2 actions if it's pressed. Does it work with "switch" statements or how do i go from here?

The code:

@IBAction func Refreshbutton(sender: AnyObject) {

switch sender.currentTitle! {
case "refresh":
Mapview.userTrackingMode = .Follow

case "refresh2":
Mapview.userTrackingMode = .FollowWithHeading

default: break


Answer Source

That would be a way to do it. However, it would be better to save your state in the class instead of using the title beacuse it may get localized in the future and because you should try to separate UI from logic. You could do something like this:

var trackingMode = .FollowWithHeading
@IBAction func Refreshbutton(sender: AnyObject) {    
   trackingMode = trackingMode == .Follow ? .FollowWithHeading : .Follow
   Mapview.userTrackingMode = trackingMode

You probably can use the map's property directly:

@IBAction func Refreshbutton(sender: AnyObject) {    
   Mapview.userTrackingMode = Mapview.userTrackingMode == .Follow ? .FollowWithHeading : .Follow

As a side note to your posted code, it would be saver if you would do

switch sender.currentTitle ?? "" {

instead of

switch sender.currentTitle! {

This way the app won't crash if no title is set, it just would use the default case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download