【发布时间】:2016-12-13 14:19:23
【问题描述】:
我有我的ViewController.class 和一个Menu.class
在Menu.class 中,我创建并设置了所有按钮,在ViewController.class 中,我将菜单添加到视图中。当我运行代码时,屏幕上会显示所有内容,但我无法按下按钮。
这就是我的 ViewController 的样子:
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 个按钮 + 标签
-
尝试更改您的 addTarget,将“self”替换为“superview”。
-
糟糕的想法 dfd。它在混乱中增加混乱。我不建议这样做。