我用以下类创建了一个新文件:
import Foundation
import UIKit
var Feld = classFeld()
class classFeld {
let button = UIButton()
func createButton() -> UIButton {
button.frame = CGRect(x: 10, y: 50, width: 200, height: 100)
button.backgroundColor=UIColor.black
button.addTarget(self, action: #selector(ButtonPressed(sender:)), for: .touchUpInside)
return button
}
@objc func ButtonPressed(sender: UIButton!) {
button.backgroundColor=UIColor.red
}
}
这是我的视图控制器:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
mainview.addSubview(Feld.createButton())
self.view.addSubview(mainview)
}
var mainview=UIView()
}
当我启动应用程序时,会创建一个黑色按钮,但是当我单击它时,它不会变成红色。如果我添加按钮而不是
mainview.addSubview(Feld.createButton())
至
self.view.addSubview(Feld.createButton())
它工作,按钮变成红色。
谁能解释一下为什么?如果我将某些内容添加到 self.view 或添加到 self.view 的子视图中,应该没有区别?