在以编程方式实例化的 xib 模板中监听输入

Listening for input in programmatically instantiated xib templates

我目前正在以编程方式添加和删除模板视图;要删除 UIView 模板,用户必须点击其中的按钮。

但是,我不确定如何让父视图控制器处理按钮输入。我希望父视图控制器知道按钮何时被按下,而不是让 xib class 处理它,否则我将不得不绕圈子,而且很快就会变得很烦人。

同样,我无法手动将按钮本身连接到 ViewController class,因为这些 xibs 是在运行时添加的。

如何让父级 ViewController 处理自定义 XIB 模板中的 UIButton 输入?

Likewise, I cannot manually connect the button itself to the ViewController class because these xibs are added in during runtime

那不是真的,因为您当然可以在 "add the xib."

时调用 addTarget(_:action:for:) 将按钮操作连接到视图控制器目标

但是,一个更酷的解决方案是使用 nil-targeted 操作在 xib 中配置您的按钮。这意味着我们不需要明确的目标;我们只需要知道操作将调用的方法的名称。视图控制器在响应链上的位置高于按钮(一旦您 "add the xib" 查看控​​制器的视图),因此当点击按钮时,将通过沿着响应链向上移动来动态找到该方法。

可以使用方法

button.addTarget(self, action: #selector(yourMethodName), for: .touchUpInside)

这里的 "button" 将是您的 xib 中按钮的引用。 "self" 将是您要在其中添加 .xib 的 viewController 的引用。