【发布时间】:2018-08-24 09:50:36
【问题描述】:
我创建了一个类,该类将创建/管理多个按钮和标签,并将它们添加到视图中,但我无法从按钮中获取要触发的操作。
这是一个没有“MakerClass”但运行良好的简单代码版本(代码在主 ViewController 中):
@objc func pressed(_ sender: UIButton!) {
print("pressed")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let backgroundButton = UIButton()
backgroundButton.backgroundColor = UIColor.green
backgroundButton.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
self.view.addSubview(backgroundButton)
backgroundButton.addTarget(self, action: #selector(pressed(_:)), for: .touchUpInside)
}
这是一个版本,我将按钮的创建放入不同的类中
视图控制器
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
MakerClass(intoView: self.view)
}
MakerClass
class MakerClass {
var backgroundButton: UIButton = UIButton()
@objc func iwastouched(_ sender: UIButton!) {
print("touched")
}
init(intoView: UIView){
backgroundButton.backgroundColor = UIColor.red
backgroundButton.frame = CGRect(x: 0, y: 200, width: 100, height: 100)
intoView.addSubview(backgroundButton)
backgroundButton.addTarget(self, action: #selector(iwastouched(_:)), for: .touchUpInside)
}
}
我用来玩这个的项目可以从here下载
由于我是 iOS 编程新手,所以我可能会走错路
【问题讨论】: