如何使用嵌套函数执行选择器?
How to perform selector with a nested function?
我有一个这样的嵌套函数,我想在用户点击我的按钮时调用 childFunc
,但它不起作用
class MyClass {
func parentFunc() {
button.addTarget(self, action: #selector(parentFunc().childFunc), for: .touchUpInside)
func childFunc() {
print("User tapped")
}
}
}
它会引发这样的错误:
Value of tuple type '()' has no member 'childFunc'
有什么方法可以用 #selector
执行 childFunc
吗?
编辑 1:
我有像这样使用闭包,但我认为这不是一个好方法,因为我必须制作另一个功能
class MyClass {
myClosure: () -> () = {}
func parentFunc() {
button.addTarget(self, action: #selector(runChildFunc), for: .touchUpInside)
func childFunc() {
print("User tapped")
}
myClosesure = childFunc
}
func runChildFunc() {
myClosure()
}
}
Is there any way to perform childFunc with #selector
没有。整个想法毫无意义。请记住,嵌套(内部)函数 并不真正存在 。它仅在 存在时 在外部函数运行 时暂时存在。外部函数 的 运行 在遇到定义时使内部函数 存在,有效地将其存储在局部变量中,以便可以从后续代码中调用在 范围内 函数中。并且像任何局部变量一样,当外部函数代码结束时,内部函数将不复存在。此外,因为它是 func 内部的局部变量,所以它的作用域不能从外部调用,即使这样的概念是有意义的——就像 func 内部的局部变量不能从在 func 之外,即使 那个 概念是有道理的。
选择器必须指向 class 实例的 方法 (其中 class 派生自 NSObject)。这是一个 Cocoa Objective-C 架构;你必须遵守 Objective-C 规则。
相反,您可以尝试以下代码来实现您的目标
class MyClass {
let button = UIButton()
@objc public func parentFunc(_ sender : UIButton?)
{
func childFunc() {
print("User tapped")
}
if sender != nil && sender.tag == 100{
childFunc()
return
}
button.addTarget(self, action: #selector(parentFunc(_:)), for: .touchUpInside)
button.tag = 100
}
}
在上面的代码中,Sender 是可选的,所以当你不想调用像 parentFunc(nil)
这样的子函数时,你可以传递 nil
我有一个这样的嵌套函数,我想在用户点击我的按钮时调用 childFunc
,但它不起作用
class MyClass {
func parentFunc() {
button.addTarget(self, action: #selector(parentFunc().childFunc), for: .touchUpInside)
func childFunc() {
print("User tapped")
}
}
}
它会引发这样的错误:
Value of tuple type '()' has no member 'childFunc'
有什么方法可以用 #selector
执行 childFunc
吗?
编辑 1: 我有像这样使用闭包,但我认为这不是一个好方法,因为我必须制作另一个功能
class MyClass {
myClosure: () -> () = {}
func parentFunc() {
button.addTarget(self, action: #selector(runChildFunc), for: .touchUpInside)
func childFunc() {
print("User tapped")
}
myClosesure = childFunc
}
func runChildFunc() {
myClosure()
}
}
Is there any way to perform childFunc with #selector
没有。整个想法毫无意义。请记住,嵌套(内部)函数 并不真正存在 。它仅在 存在时 在外部函数运行 时暂时存在。外部函数 的 运行 在遇到定义时使内部函数 存在,有效地将其存储在局部变量中,以便可以从后续代码中调用在 范围内 函数中。并且像任何局部变量一样,当外部函数代码结束时,内部函数将不复存在。此外,因为它是 func 内部的局部变量,所以它的作用域不能从外部调用,即使这样的概念是有意义的——就像 func 内部的局部变量不能从在 func 之外,即使 那个 概念是有道理的。
选择器必须指向 class 实例的 方法 (其中 class 派生自 NSObject)。这是一个 Cocoa Objective-C 架构;你必须遵守 Objective-C 规则。
相反,您可以尝试以下代码来实现您的目标
class MyClass {
let button = UIButton()
@objc public func parentFunc(_ sender : UIButton?)
{
func childFunc() {
print("User tapped")
}
if sender != nil && sender.tag == 100{
childFunc()
return
}
button.addTarget(self, action: #selector(parentFunc(_:)), for: .touchUpInside)
button.tag = 100
}
}
在上面的代码中,Sender 是可选的,所以当你不想调用像 parentFunc(nil)