iOS Swift通关闭作为属性? [英] iOS Swift Pass Closure as Property?

查看:72
本文介绍了iOS Swift通关闭作为属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个自定义的UIView,我们称之为MyCustomView。在这个视图内是一个UITextField属性。假设我的目标是能够创建一个MyCustomView的实例并将它添加到某个视图控制器,我想让该视图控制器能够处理对该文本字段执行的操作。例如,如果我在文本字段内的键盘上点击返回,我可能想做一些操作 - 让我举一个例子,我想到了一些objective-c伪装代码:

Let's say I have a custom UIView, lets call it MyCustomView. Inside this view is a UITextField property. 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. 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:

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

然后在MyCustomView类中,我将执行如下操作:

And then inside the MyCustomView class I would do something like:

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



我希望customView是UITextFieldDelegate,这样每次我这个我不必将所有的委托方法添加到我添加它的视图控制器,而是有一个实现只是 无论 我传递给

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?

推荐答案

当然,你可以这样做。 Swift具有第一类函数,所以你可以做类似于直接传递函数的东西。请记住,函数本身实际上是幕后的闭包。这里有一个基本的例子:

Sure, you can do this. Swift has first class functions, so you are able to do things like directly pass functions around like variables. 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!()

下面是使用闭包a String parameter。

And here is the same example using closures that can take a String parameter.

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

这篇关于iOS Swift通关闭作为属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆