iOS-Swift.MVC到MVVM重构.使用Delegate方法处理IBActions



使用故事板构建UI。

Swift 5。

我的设置如下:

文件1-UI

@objc public protocol TestDelegateViewDelegate: class {
**func primaryAction()**
}
class TestDelegateView: UIView {
@IBOutlet private weak var button: UIButton!
weak var delegate: TestDelegateViewDelegate?

@IBAction private func primaryActionPressed(_ sender: UIButton) {
print("print if before delegate executes")
**delegate?.primaryAction()**
print("print if after delegate executes")
}
}

文件2-ViewController

extension TestDelegateViewController : TestDelegateViewDelegate {
**func primaryAction() {**
self.dismiss(animated: true, completion: nil)
print("print if delegate executes")
}

当我尝试这个代码时,我的代码确实打印了我所有的打印语句,然而-我得到这个错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '-[Project.TestDelegateView buttonAction]: 
unrecognized selector sent to instance 0x11bc0d2a0'

1-我使用代理是否错误?我需要保留IBOutlets和IBActions在视图中。

2-我可能用错MVVM了吗?

3-这种设计模式的最佳实践方法是什么?

4-为什么我会在这里得到这个错误?它发生在所有代码运行之后。

非常感谢你的帮助。

一些东西——可能是故事板中的一个按钮——连接到一个名为buttonAction的函数。在您的代码中,IBAction被称为primaryActionPressed

发生这种情况的通常方式是重命名代码函数,同时不重置其情节提要连接以匹配。

我找到了解决这个问题的方法——如何完整地实现MVVM设计模式。使用UIView中的操作。然而,通过使用委托协议,将操作主要保留在View控制器中。

协议

@objc public protocol TestDelegateViewDelegate: class {
**func primaryAction()**
}

UIView文件

class TestDelegateView: UIView {
@IBOutlet private weak var button: UIButton!
weak var delegate: TestDelegateViewDelegate?

@IBAction private func primaryActionPressed(_ sender: UIButton) {
print("print if before delegate executes")
**delegate?.primaryAction()**
print("print if after delegate executes")
}
init(delegate: TestDelegateViewDelegate) {
self.delegate = delegate
}
}

查看控制器

class TestDelegateViewController: UIViewController {
var view: TestDelegateView?
viewDidLoad() {
view = TestDelegateView(delegate: self)
}
}
extension TestDelegateViewController : TestDelegateViewDelegate {
**func primaryAction() {**
self.dismiss(animated: true, completion: nil)
print("print if delegate executes")
}

最新更新