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個按鈕+標籤 –