2016-12-13 45 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") 
    } 
}