2016-12-13 48 views
1

調用的UIButton按我有我的ViewController.classMenu.class斯威夫特:從另一個類

在創建和安裝所有的按鈕,並在ViewController.class我的菜單添加到視圖的Menu.class。當我運行代碼時,所有內容都顯示在屏幕上,但我無法按下按鈕。

這是我的視圖控制器看起來像:

import UIKit 

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let menu = Menu() 
     menu.setupView(controller: self, width: 600, height: 120) 
     self.view.addSubview(menu) 

     // Do any additional setup after loading the view, typically from a nib. 
    } 
} 

這是我的菜單:

import Foundation 
import UIKit 

class Menu: UIView{ 

    func setupView(controller: ViewController, width: CGFloat, height: CGFloat){ 

     let newGame = UIButton(frame: CGRect(x: controller.view.center.x, y: 300, width: width, height: height)) 
     newGame.center = CGPoint(x: controller.view.center.x, y: 300) 
     newGame.setTitle("New Game", for: .normal) 
     newGame.backgroundColor = UIColor.gray 
     newGame.titleLabel?.font = UIFont(name: "Helvetica", size: 42) 
     newGame.setTitleColor(UIColor.black, for: .normal) 
     newGame.addTarget(self, action: #selector(Menu.newGame), for: .touchUpInside) 
     self.addSubview(newGame) 

    } 
    func newGame(){ 
     print("New Game") 

    } 
} 

什麼是我的錯誤。我是否需要進行更多初始化,以便能夠檢測到新聞?

+0

嗯,我c/c你的代碼,它甚至不會爲我編譯。首先我想知道,爲什麼Menu不直接從UIButton中遺傳?你打算有多個按鈕嗎?如果是,有多少?如果你想有一個合適的代碼,你應該再次考慮你的概念。如果您只想知道爲什麼它會變壞,那是因爲您的框架設置不正確 –

+0

我打算有2個按鈕和1個標籤。我刪除了其他兩件事的代碼,並且菜單中缺少一個}。對不起。 –

+0

}不是唯一的問題。無論如何,如果我是你,我會刪除你的菜單,我會直接在ViewController中創建我的2個按鈕+標籤 –

回答

2

這是你應該怎麼做的。重複buttonTwo和label的操作。在viewDidLoad()中設置視圖並在viewDidLayoutSubviews中設置框架。

如果你繼承任何的UIView,您應該設置如果你想顯示的tableView當你點擊newGame然後創建一個新的UIViewController)在layoutSubviews幀(

。在其中添加一個UITableView,就像你在ViewController中添加按鈕和標籤的方式一樣

import UIKit 

class ViewController: UIViewController { 

    let buttonOne = UIButton() 
    let buttonTwo = UIButton() 
    let label = UILabel() 

    override func viewDidLoad() { 
    super.viewDidLoad() 

    buttonOne.backgroundColor = UIColor.gray 
    buttonOne.setTitle("New Game", for: .normal) 
    buttonOne.titleLabel?.font = UIFont(name: "Helvetica", size: 42) 
    buttonOne.setTitleColor(UIColor.black, for: .normal) 
    buttonOne.addTarget(self, action: #selector(newGame), for: .touchUpInside) 

    view.addSubview(buttonOne) 
    view.addSubview(buttonTwo) 
    view.addSubview(label) 
    } 

    override func viewDidLayoutSubviews() { 
    buttonOne.frame = CGRect(x: 0, y: 300, width: 600, height: 120) 
    buttonOne.center.x = self.view.center.x 
    } 

    func newGame(sender: UIButton?) { 
    print("New Game") 
    } 
}