【发布时间】:2022-01-25 23:08:36
【问题描述】:
我正在自学 UIKit,目前正在以编程方式创建控件和其他视图。
我尝试将按钮从 ViewController 中重构到它们自己的视图中。
This 是我一直遵循的教程,将其改编为我自己的项目。这就是我所拥有的:
ViewController.swift:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let buttonBar = ButtonBar(frame: CGRect(x: 0, y: 0, width: 400, height: 100), buttonAction: buttonWasPressed)
view.addSubview(toolbar)
}
func buttonWasPressed() {
print("Button Was Pressed")
}
}
以及重构的按钮,ButtonBar.swift:
import UIKit
class ButtonBar: UIView {
var buttonAction: (() -> Void)?
init(frame: CGRect, buttonAction: @escaping() -> Void) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
let buttonA = UIButton(type: .system)
buttonA.setTitle("A", for: .normal)
buttonA.frame = CGRect(x:20, y:20, width: 100, height: 100)
buttonA.addTarget(self, action: #selector(self.buttonWasPressed), for: .touchUpInside)
addSubview(buttonA)
// more buttons to come...
}
@objc func buttonWasPressed() {
buttonAction?()
}
}
当按钮被按下时,我希望从 ViewController 打印消息“Button Was Pressed”,但这并没有发生。我做错了什么?
我对 UIKit、Swift 和 iOS 开发的了解有限。即使按照上面的教程进行操作,我仍然不完全理解这段代码应该如何工作。
最后,这是将大量按钮重构为单个视图的正确方法吗?
谢谢!
【问题讨论】:
标签: swift model-view-controller uiviewcontroller uikit