iOS-Swift从MVC到MVVM重构使用Delegate方法处理IBAction

问题描述

使用情节提要构建UI。

迅速5。

我的设置如下:

文件1-用户界面

@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和IBAction。

2-我使用MVVM可能是错误的吗?

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

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

非常感谢您的帮助。

解决方法

某些东西(可能是情节提要中的一个按钮)已连接到名为buttonAction的函数。在您的代码中,IBAction被称为primaryActionPressed

这种情况的通常发生方式是重命名代码功能,而不重置其故事板连接以匹配。

,

我找到了解决此问题的方法-如何完全实现MVVM设计模式。来自UIView的动作。但是,通过使用委托协议,大多数动作仍在View控制器中进行。

协议

select a.*
from mytable t1
where exists (
    select 1
    from mytable t1
    where t1.al = t.al and t1.date = t.date and t1.id <> t.id
)

UIView文件

@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")
  }

  init(delegate: TestDelegateViewDelegate) {
     self.delegate = delegate
   }

 }

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...