我可以让#selector引用Swift中的闭包吗? [英] Can I make #selector refer to a closure in Swift?
问题描述
我想使方法的选择器
参数引用一个闭包属性,它们都存在于同一作用域中。例如,
func backgroundChange(){
self.view.backgroundColor = UIColor.blackColor()
self.view.alpha = 0.55
let backToOriginalBackground = {
self.view.backgroundColor = UIColor.whiteColor()
self.view.alpha = 1.0
}
NSTimer.scheduledTimerWithTimeInterval(0.5,target:self,选择器:#selector(backToOriginalBackground),userInfo:nil,重复:false)
}
但是,这显示了一个错误: #selector的参数不能引用属性
。 / p>
当然,我可以定义一个新的单独方法,并将闭包的实现移到该方法上,但是对于这样的小实现,我想保持节俭。
是否可以将 #selector
参数设置为闭包?
正如@ gnasher729指出的那样,这是不可能的,因为选择器只是方法的名称,而不是方法的名称。 ds本身。在一般情况下,我在这里使用 dispatch_after
,但是在这种情况下,更好的IMO工具是 UIView.animateWithDuration
,因为它正是该功能的目的,并且非常容易调整过渡:
UIView.animateWithDuration(0 ,延迟:0.5,选项:[],动画:{
self.view.backgroundColor = UIColor.whiteColor()
self.view.alpha = 1.0
},完成:nil)
I want to make a selector
argument of my method refer to a closure property, both of them exist in the same scope. For example,
func backgroundChange() {
self.view.backgroundColor = UIColor.blackColor()
self.view.alpha = 0.55
let backToOriginalBackground = {
self.view.backgroundColor = UIColor.whiteColor()
self.view.alpha = 1.0
}
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(backToOriginalBackground), userInfo: nil, repeats: false)
}
However, this shows an error: Argument of #selector cannot refer to a property
.
Of course I can define a new, separate method and move the implementation of the closure to it, but I want to keep it frugal for such a small implementation.
Is it possible to set a closure to #selector
argument?
As @gnasher729 notes, this is not possible because selectors are just names of methods, not methods themselves. In the general case, I'd use dispatch_after
here, but in this particular case, the better tool IMO is UIView.animateWithDuration
, because it's exactly what that function is for, and it's very easy to tweak the transition:
UIView.animateWithDuration(0, delay: 0.5, options: [], animations: {
self.view.backgroundColor = UIColor.whiteColor()
self.view.alpha = 1.0
}, completion: nil)
这篇关于我可以让#selector引用Swift中的闭包吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!