我必须使用协议/委托让 ViewController 执行在另一个 class 中创建的 UIButton 的操作吗?

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

我创建了一个 UIButton 作为 UIView 的子视图 Class。我想将该 UIView 作为子视图添加到 UIViewController Class。我想将 UIViewController Class 中的目标操作添加到 UIButton。在我下面的示例中,当您点击我的 UIButton 时,它应该打印 "Hello the button was pressed!"。但是,没有任何反应。为什么是这样?我知道还有其他方法可以实现这一目标。为什么我的方法不起作用?使用其他技术实现此方法的优缺点是什么?

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)
}
}

你需要给 myView 一个尺寸。

喜欢:

override func viewDidLoad() {
    super.viewDidLoad()

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