在我的自定义视图的控制器中创建自定义 IBAction [英] Create Custom IBAction in Controller of my Custom View
问题描述
首先我不能发布任何代码,但我会尽量描述我的问题.
firstly I cannot post any Code but I´ll try to describe my problem as best as I can.
好的.我创建了一个自定义 Swift 视图文件作为 view.xib
并将它加载到我的 view.swift
我加载了那个 Xib
.Xib 是 imageview
上方的一个简单的 label
.我可以在我的 view.swift
文件中创建我的 IBOutlet
,例如切换图像或更改标签.view.swift
只是扩展了 UIView
.
Ok. I created a Custom Swift View File as view.xib
and loading it in my view.swift
I loaded that Xib
. The Xib is a simple label
above a imageview
.
I can create my IBOutlet
in my view.swift
file and e.g. switch the image or change the label. view.swift
simply extends UIView
.
所以现在我将这个视图集成到我的 Storyboard
中,它有一个控制器(我们称之为 otherVC.swift
).现在 otherVC.swift
想要获取 view.swift
被触摸的信息.我尝试设置 IBAction
但没有设置选项,仅在 IBOutlet
上设置.在使用 Googe 之后,我发现 UiControl
类具有设置 IBAction
的机制.
So now I integrated this view in my Storyboard
which has a Controller (lets call it otherVC.swift
). Now otherVC.swift
wants to get info that the view.swift
is touched. I tried setting a IBAction
but there no option to set on, just on IBOutlet
. After some Googe I found that the Class UiControl
has those mechanics to set a IBAction
.
所以我 view.swift
不再扩展 UIView
而是现在 UIControl
.之后我可以创建一个带有触摸事件的 IBAction
.(如触摸或触摸内部)在模拟器中使用视图运行应用程序时,我可以单击视图,但不会调用 IBAction.
So I view.swift
no longer extends UIView
but now UIControl
. After that I Could create an IBAction
with a touch event. (like touch down or touch inside) When running the app with the view in the simulator I can click the view but the IBAction wont be callled.
所以我的问题是如何在其他 VC 中为我的视图设置 IBAction
或者为特定视图创建我自己的 IBActions
.
So my question is how can I set a IBAction
for my View in a other VC or maybe create my own IBActions
for the specific view.
再次..无法发布代码.欢迎带有工作示例的片段或链接
谢谢!
推荐答案
我认为创建自定义 IBAction
会很困难(如果不是不可能的话),但是您的问题还有许多其他解决方案,例如委托、通知或关闭.我建议您使用闭包,因为我认为这是最简单的方法.
I think that it will be hard to create a custom IBAction
(if not impossible), but your problem has many other solutions like delegates, notifications, or closures. I recommend that you use closures as it is the simplest way in my opinion.
以下是如何使用闭包实现这一目标的示例代码:
Below is example code of how you could achieve this with closures:
class View: UIView {
var someButtonTapped: (UIButton) -> Void = { _ in }
@IBAction private func someButtonTappedAction(_ sender: UIButton) {
someButtonTapped(sender)
}
}
然后在您的控制器中添加:
Then in your controller, add this:
objectOfYourCustomView.someButtonTapped = { (sender: UIButton) in
// Handle action
}
这篇关于在我的自定义视图的控制器中创建自定义 IBAction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!