iOS的Swift通过closures属性?

比方说,我有一个自定义的UIView,让我们称之为MyCustomView。 在这个视图里面是一个UITextField属性。 假设我的目标是能够创build一个MyCustomView的实例,并将其添加到某个视图控制器,我希望该视图控制器能够处理在该文本字段上采取的行动。 例如,如果我在文本字段中的键盘上点击“返回”,我可能想要做一些操作 – 让我举一个例子来说明我用一些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; } 

我想自定义视图是UITextFieldDelegate,所以每次我这样做,我不会把所有的委托方法添加到视图控制器,我将它添加到,而是有一个单一的实现,只是做任何我传递给它…如何迅速做到这一点?

当然,你可以做到这一点。 Swift具有一stream的function,所以你可以做像直接传递函数一样的variables。 请记住,函数本身实际上是在幕后closures的。 这是一个基本的例子:

 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!")