2016-07-06 5 views
0

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

答えて

0

myViewにサイズを指定する必要があります。

同様:

override func viewDidLoad() { 
    super.viewDidLoad() 

    myView.frame = view.bounds 
    self.view.addSubview(myView) 
    myView.myButton.addTarget(self, action: #selector(hello), forControlEvents: UIControlEvents.TouchUpInside) 
} 
関連する問題