简体   繁体   English

iOS Swift Pass关闭属性?

[英]iOS Swift Pass Closure as Property?

Let's say I have a custom UIView, lets call it MyCustomView. 假设我有一个自定义UIView,我们称之为MyCustomView。 Inside this view is a UITextField property. 在这个视图中是一个UITextField属性。 Suppose my goal is to be able to create an instance of MyCustomView and add it to some view controller somewhere, and I want that view controller to be able to handle actions taken on that text field. 假设我的目标是能够创建一个MyCustomView实例并将其添加到某个视图控制器,我希望该视图控制器能够处理对该文本字段采取的操作。 For example, if I hit "return" on the keyboard within the text field, I may want to do some action - let me give an example of what I'm envisioning with some objective-c psuedo code: 例如,如果我在文本字段中的键盘上点击“return”,我可能想要做一些动作 - 让我举一个例子,说明我想象的一些Objective-c伪代码:

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

And then inside the MyCustomView class I would do something like: 然后在MyCustomView类中我会做类似的事情:

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

I'd like the customView to be the UITextFieldDelegate so that every time I do this I won't have to add all the delegate methods to the view controllers I'm adding it to, but rather have a single implementation that just does whatever I pass to it... How would one go about doing this in swift? 我希望customView成为UITextFieldDelegate,这样每次我这样做时,我都不必将所有委托方法添加到我正在添加它的视图控制器中,而是只有一个实现,只做我做的任何事情传递给它......如何快速地做到这一点?

Sure, you can do this. 当然,你可以做到这一点。 Swift has first class functions, so you are able to do things like directly pass functions around like variables. Swift具有一流的函数,因此您可以执行诸如直接传递函数之类的变量。 Keep in mind, functions themselves are in fact closures behind the scenes. 请记住,功能本身实际上是幕后的闭包。 Here's a basic example: 这是一个基本的例子:

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

And here is the same example using closures that can take a String parameter. 以下是使用可以采用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