UIView クラスのサブビューとして UIButton を作成しました。その UIView をサブビューとして UIViewController クラスに追加したいと思います。UIViewController クラスのターゲット アクションを UIButton に追加したいと思います。以下の例では、UIButton をタップすると、「こんにちは、ボタンが押されました!」と表示されます。しかし、何も起こりません。どうしてこれなの?これを達成する他の方法があることを理解しています。私のやり方がうまくいかないのはなぜですか? 他の手法を使用してこれを達成することの長所と短所は何ですか?
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)
}
}