1

So I have a FeatureTutorialDelegate protocol with one buttonPressed() method. I have a FeatureTutorialViewController that functions as the delegate. A PageViewController calls these FeatureTutorialViewController classes. The different pages have multiple buttons.

How do I make the different buttons do different things with the buttonPressed() method? I need the button to dismiss the tutorial, open other ViewControllers, etc, depending on which tutorial page the user taps the button on.

Marcus Ziadé
  • 650
  • 2
  • 7
  • 17

2 Answers2

1

Create an enum for the actions.

enum Action {
    case .dismiss
    case .open
}

protocol ADelegate {
    func buttonPressed(action: Action)
}

class A(){
    func navigate(){
        let b = B()
        b.delegate = self
    }
}

extension A: ADelegate {
    func buttonPressed(action: Action) {
        if  action == .dismiss {

        } else if action == .open{

        }
    }
}

class B {
    var delegate: ADelegate?

    func dismiss(){
        self.delegate?.buttonPressed(action: .dismiss)
    }

    func open(){
        self.delegate?.buttonPressed(action: .dismiss)
    }
}

Read this thread should you need to know why you should not use string as the other answer suggests.

What are enums and why are they useful?


You may define multiple methods in the protocol. Doing so you avoid using if-else statement. It is cleaner.

protocol ADelegate {
    func dismiss()
    func open()
    func navigate()
}
mahan
  • 12,366
  • 5
  • 48
  • 83
0

you need to pass variable in delegate method so when delegate is call check that variable and perform action accordingly.

protocol MoveFeatureTutorial {
    func buttonPressed(check: String)
}

var delegate: MoveFeatureTutorial

put below code in button action method

self.delegate?.buttonPressed(check: "For Button A")
self.delegate?.buttonPressed(check: "For Button B")

It's is the method that that protocol

func buttonPressed(check: String?) {
       if check == "For Button A" {
print(check)
} else if check == "For Button B" {
print(check)
} else {
print(check)
}
    }