1
调用的UIButton按我有我的ViewController.class
和Menu.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")
}
}
什么是我的错误。我是否需要进行更多初始化,以便能够检测到新闻?
嗯,我c/c你的代码,它甚至不会为我编译。首先我想知道,为什么Menu不直接从UIButton中遗传?你打算有多个按钮吗?如果是,有多少?如果你想有一个合适的代码,你应该再次考虑你的概念。如果您只想知道为什么它会变坏,那是因为您的框架设置不正确 –
我打算有2个按钮和1个标签。我删除了其他两件事的代码,并且菜单中缺少一个}。对不起。 –
}不是唯一的问题。无论如何,如果我是你,我会删除你的菜单,我会直接在ViewController中创建我的2个按钮+标签 –