【发布时间】:2018-07-17 08:52:40
【问题描述】:
我用以下类创建了一个新文件:
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
}
}
这是我的 ViewController:
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 的子视图中应该没有区别?
【问题讨论】:
-
你如何设置主视图的框架?
-
我根本没有设置。它适用于设置它。谢谢
标签: ios swift uiview uibutton addtarget