繁体   English   中英

iOS Swift Pass关闭属性?

[英]iOS Swift Pass Closure as Property?

假设我有一个自定义UIView,我们称之为MyCustomView。 在这个视图中是一个UITextField属性。 假设我的目标是能够创建一个MyCustomView实例并将其添加到某个视图控制器,我希望该视图控制器能够处理对该文本字段采取的操作。 例如,如果我在文本字段中的键盘上点击“return”,我可能想要做一些动作 - 让我举一个例子,说明我想象的一些Objective-c伪代码:

MyCustomView *myView = [[MyCustomView alloc] initWithFrame:CGRectMake(10,10,100,100)];
myView.textField.actionBlock = { /* do stuff here! */ }
[self.view addSubview:myView];

然后在MyCustomView类中我会做类似的事情:

- (BOOL)textFieldShouldReturn:(UITextField *)textField  {
    self.actionBlock();
    return NO;
}

我希望customView成为UITextFieldDelegate,这样每次我这样做时,我都不必将所有委托方法添加到我正在添加它的视图控制器中,而是只有一个实现,只做我做的任何事情传递给它......如何快速地做到这一点?

当然,你可以做到这一点。 Swift具有一流的函数,因此您可以执行诸如直接传递函数之类的变量。 请记住,功能本身实际上是幕后的闭包。 这是一个基本的例子:

class MyClass {
    var theClosure: (() -> ())?

    init() {
        self.theClosure = aMethod
    }

    func aMethod() -> () {
        println("I'm here!!!")
    }
}


let instance = MyClass()
if let theClosure = instance.theClosure {
    theClosure()
}

instance.theClosure = {
    println("Woo!")
}
instance.theClosure!()

以下是使用可以采用String参数的闭包的相同示例。

class MyClass {
    var theClosure: ((someString: String) -> ())?

    init() {
        self.theClosure = aMethod
    }

    func aMethod(aString: String) -> () {
        println(aString)
    }
}

let instance = MyClass()
if let theClosure = instance.theClosure {
    theClosure(someString: "I'm the first cool string")
}

instance.theClosure = {(theVerySameString: String) -> () in
    println(theVerySameString)
    someThingReturningBool()
}
instance.theClosure!(someString: "I'm a cool string!")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM