Swift Selector

前端之家收集整理的这篇文章主要介绍了Swift Selector前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

看了喵神的Swifter 100个必备的小tips总结下

swift中不支持@selector关键字,将SEL重新定义为结构体了。

但是NSSelectorFromString()依然可以使用,但是获取方法名的规则有点变动。

1.不带参数的方法

func normalSelector()

{

NSLog("normal")

}


let ts = TestSelector()

let ns = Selector("normalSelector")

ts.performSelector(ns)


2.带参数的方法,参数间不能出现空格,否则无法识别(我在swift2.0 Xcode7.1测试的)

func normalWithPara(name:String)

{

NSLog("para = %s",name)

}

func normalWithMorePara(name:String,age : Int)

{

NSLog("more para = %s %d",name,age)

}


let np = Selector("normalWithPara:")

ts.performSelector(np,withObject: "np")

let nmp = Selector("normalWithMorePara:age:")

ts.performSelector(nmp,withObject: "nmp",withObject:1)


"normalWithMorePara:age:" 参数中如果添加个空格变成 "normalWithMorePara: age:" 就会残忍的崩溃。。。


3.带外部参数名的方法,如果第一个参数有外部变量名,则需要方法名+With+外部参数名(第一个字母要大些),之后的参数有外部变量名的都是用外部变量名。


func outsideSelectorWithMorePara(name nm:String,age ag:Int)

{

NSLog("nm = %s,ag = %d",nm,ag)

}


func outsideSelector(name nm:String)

{

NSLog("nm = %s",nm)

}

let os = Selector("outsideSelectorWithName:")

ts.performSelector(os,withObject:"os")

let oms = Selector("outsideSelectorWithMoreParaWithName:age:")

ts.performSelector(oms,withObject: "oms",withObject: 1)

原文链接:https://www.f2er.com/swift/325430.html

猜你在找的Swift相关文章