Ryan Bittorf Ryan Bittorf - 4 months ago 10
Swift Question

Must I use protocols / delegation to have a ViewController perform an action of a UIButton created in another class?

I created a UIButton as a subview of a UIView Class. I would like to add that UIView as a subview to a UIViewController Class. I would like to add a target action in the UIViewController Class to the UIButton. In my example below, when you tap on my UIButton, it should print "Hello the button was pressed!". However, nothing happens. Why is this? I understand there are other ways of achieving this. Why doesn't my way work and what are the pros and cons of achieving this using other techniques?

import UIKit

class ViewController: UIViewController {

let myView = MyView()

override func viewDidLoad() {
super.viewDidLoad()

self.view.addSubview(myView)
myView.myButton.addTarget(self, action: #selector(hello), forControlEvents: UIControlEvents.TouchUpInside)
}

func hello()
{
print("Hello the button was pressed!")
}



}

class MyView : UIView
{
var myMainView = UIView(frame: CGRectZero)
var myButton = UIButton(frame: CGRectZero)

override init(frame:CGRect){
super.init(frame:frame)

setUpViews()
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

func setUpViews()
{
print("Set up views")
myMainView.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width , UIScreen.mainScreen().bounds.height)
myMainView.backgroundColor = UIColor.yellowColor()
self.addSubview(myMainView)

myButton.frame = CGRectMake(100, 100, 200, 40)
myButton.backgroundColor = UIColor.darkGrayColor()
myMainView.addSubview(myButton)
}
}

Answer

You need to give myView a size.

Like:

override func viewDidLoad() {
    super.viewDidLoad()

    myView.frame = view.bounds
    self.view.addSubview(myView)
    myView.myButton.addTarget(self, action: #selector(hello), forControlEvents: UIControlEvents.TouchUpInside)
}
Comments