[英]Swift class with uibutton.addTarget to UIView not working
I created a new file with the following class: 我使用以下类创建了一个新文件:
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
}
}
And this is my ViewController: 这是我的ViewController:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
mainview.addSubview(Feld.createButton())
self.view.addSubview(mainview)
}
var mainview=UIView()
}
When I start the app a black button is created but when I click on it it doesnt color red. 当我启动应用程序时,会创建一个黑色按钮,但是当我单击它时,它不会变成红色。 If I add the button instead of 如果我添加按钮而不是
mainview.addSubview(Feld.createButton())
to 至
self.view.addSubview(Feld.createButton())
it works and the button turns red. 它起作用并且按钮变为红色。
May I anyone explain me why? 我可以向我解释为什么吗? It should make no difference if I add something to self.view or to a subview which is then added to self.view? 如果我向self.view或子视图中添加一些内容,然后再将其添加到self.view中,这应该没有什么区别?
因为您需要给它一个框架并将其添加到self.view
var mainview = UIView()
This is because you are just initializing a UIView
without giving it any frame and adding it to the main view. 这是因为您只是在初始化UIView
而不给它任何框架并将其添加到主视图中。
You need to give frame to your mainview also. 您还需要给主视图框架。 For example : 例如 :
class ViewController: UIViewController {
var mainview = UIView()
override func viewDidLoad() {
super.viewDidLoad()
mainview.frame = CGRect(x: 10, y: 50, width: 300, height: 300)
self.view.addSubview(mainview)
mainview.addSubview(Feld.createButton())
}
}
Here is changes on ViewController
class and working fine: 这是ViewController
类的更改,并且工作正常:
class ViewController: UIViewController {
var mainview: UIView!
override func viewDidLoad() {
super.viewDidLoad()
mainview = UIView(frame: self.view.bounds)
mainview.addSubview(Feld.createButton())
self.view.addSubview(mainview)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.