Viraat Das
Viraat Das

Reputation: 38

Create a button that goes to another class in Swift

I have a button that I programmatically created. I want to it to execute the methods in another class when pressed, programmatically. This is part of my horizontal scroll view code.

 let button1 = UIButton(frame: CGRect.zero)
 button1.setImage(UIImage(named: "bell.png"), for: UIControlState.normal)
 horizontalScrollView.addItem(button1)

I want button1 one to open another class and execute methods in there.

Upvotes: 0

Views: 570

Answers (1)

Pratyush Pratik Sinha
Pratyush Pratik Sinha

Reputation: 714

If you want to perform any method on action in another class, you have to use protocol.

//Outside 1st class

protocol abc {
     func xyz()
}

//Inside 1st class

var delegate: abc?

//Inside 1st class on action

self.delegate.xyz()

//Inside 2nd class you want to perform method

extension 2nd: abc {
    func xyz(){
      //code 
   }
}

//Inside 2nd class where the instantiate process is performed

let obj = 2nd initialiser
obj.delegate = self

Hope this helps.

Upvotes: 2

Related Questions