2018年新的開始免钻,好好的整理一下Swift知識(shí)點(diǎn)彼水,希望在整理過程中提升自己。
1.swift 4.0 取消了 Selector("cyanButtonClick") 這種寫法.
class ViewController: UIViewController {
@IBOutlet weak var buttonA: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//錯(cuò)誤寫法
buttonA.addTarget(self,
action: Selector("buttonActionA"),
for: .touchUpInside)
//正確寫法
buttonA.addTarget(self,
action: NSSelectorFromString("buttonActionA"),
for: .touchUpInside)
}
func buttonActionA(){
print("text for selector")
}
//以上寫法已經(jīng)被swift4.0取消极舔,如果繼續(xù)使用會(huì)被報(bào)“Use '#selector' instead of explicitly constructing a 'Selector' "
2.我們在開發(fā)過程中通常會(huì)這樣寫凤覆,坦率的講這樣寫沒什么問題,但是不夠優(yōu)雅
class ViewController: UIViewController {
@IBOutlet weak var buttonA: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//防止方法名重復(fù)拆魏,在方法前面跟上所在類以區(qū)別
buttonA.addTarget(self,
action: #selector(ViewController.buttonActionA),
for: .touchUpInside)
}
func buttonActionA(){
print("text for selector")
}
3.如何訪問我們的private私有方法盯桦,則是在前面加@Objc變成運(yùn)行時(shí)澡绩。
class ViewController: UIViewController {
@IBOutlet weak var buttonA: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//當(dāng)然如果不需要區(qū)分則可以去掉ViewController,也可以用self代替ViewController
let methodObjc = #selector(ViewController.buttonActionObjc)
buttonA.addTarget(self,
action: methodObjc,
for: .touchUpInside)
}
func buttonActionObjc(){
print("text for selectorObjc")
}
4.相同方法名不同參數(shù)俺附,可以用 as 區(qū)分
class ViewController: UIViewController {
@IBOutlet weak var buttonA: UIButton!
@IBOutlet weak var buttonB: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let methodA = #selector(buttonActionA as () -> ())
let methodB = #selector(buttonActionB as (UIButton) -> ())
buttonA.addTarget(self,
action: methodA,
for: .touchUpInside)
buttonB.addTarget(self,
action: methodB,
for: .touchUpInside)
}
func buttonActionA(){
print("text for buttonActionA")
}
func buttonActionB(){
print("text for buttonActionB")
}
5.Swift 3.0 中加入了 Selector 引用變量(不可為常量)的 getter 和 setter 方法:
相關(guān)鏈接:https://github.com/apple/swift-evolution/blob/master/proposals/0064-property-selectors.md
一直在找使用場景:a.可以判斷屬性是否包含getter 和 setter。 b.可以結(jié)合responds方法使用溪掀。
class Person: NSObject {
dynamic var firstName: String
dynamic let lastName: String
dynamic var fullName: String {
return "\(firstName) \(lastName)"
}
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
let firstNameGetter = #selector(getter: Person.firstName)
let firstNameSetter = #selector(setter: Person.firstName)
6.比較優(yōu)雅的寫法可以把Selector定義成extension事镣,包含所有定義的selector
extension Selector {
static let methodA = #selector(ViewController.buttonActionA)
}
class ViewController: UIViewController {
@IBOutlet weak var buttonA: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
buttonA.addTarget(self,
action: .methodA,
for: .touchUpInside)
}
func buttonActionA(){
print("text for selector")
}