Swift 日漸成熟,如今已經(jīng)發(fā)展到3.0 版本。本文介紹iOS開發(fā)中常用的技能---頁面?zhèn)髦怠#≒S:熟知OC更容易理解)
直接通過控制器提供變量傳值
首先我們創(chuàng)建兩個控制器,命名為ViewController, FirstViewController。
下面是ViewController(根控制器)的代碼:
//懶加載一個btn
lazy private var nextPage:UIButton! = {
let nextPage = UIButton.init(type: UIButtonType.roundedRect)
nextPage.backgroundColor = UIColor.red
nextPage.center = CGPoint.init(x: 0, y: 300)
return nextPage
}()
//添加btn
nextPage.setTitle("跳轉(zhuǎn)到下一頁面", for: .normal)
nextPage.addTarget(self, action: #selector(pushToPage(_:)), for: .touchUpInside)
nextPage.sizeToFit()
view.addSubview(nextPage)
//添加事件
func pushToPage(_ button:UIButton) {
let otherPage = FirstViewController()
otherPage.labelText = "從上一個頁面?zhèn)鱽淼闹?
navigationController?.pushViewController(otherPage, animated: true)
}
FirstViewController 里面則加載一個label,用于顯示傳遞過來的值。
//在FirstVC懶加載一個label
lazy private var label:UILabel! = {
let label = UILabel()
label.backgroundColor = UIColor.blue
label.center = CGPoint.init(x: 200, y: 300)
return label
}()
//在FirstVC里面設(shè)置一個變量
var labelText:String?
此時,則可以通過在根控制器中push事件來得到傳遞來的值。
otherPage.labelText = "從上一個頁面?zhèn)鱽淼闹?
上一個方法是最簡單的方法。接下來以上述方法為基礎(chǔ),講述一下協(xié)議傳值。
協(xié)議傳值(回傳)
在上述的ViewController(根控制器)中創(chuàng)建一個協(xié)議(代理)。
//創(chuàng)建一個協(xié)議
protocol returnValueDelegate{
func returnValue(params:String)
}
并且遵從代理
接下來在根視圖中添加一個label控件來顯示傳遞過來的值。
lazy private var firstlabel:UILabel! = {
let label = UILabel()
label.backgroundColor = UIColor.blue
label.center = CGPoint.init(x: 200, y: 300)
return label
}()
在傳遞另一頁面的事件中添加協(xié)議
otherPage.returnValueDelegate = self
此時,即可以通過回傳協(xié)議的值來得到當(dāng)前的值了,FirstVC中
func toLastPage(_ button: UIButton){
returnValueDelegate?.returnValue(params: "我是姚")
_ = navigationController?.popViewController(animated: true)
}
通知傳值
通知傳值也是比較簡單的,如下所示
在根控制器中先添加通知的方法
//添加通知
NotificationCenter.default.addObserver(self, selector: #selector(notificationValue(_:)), name: NSNotification.Name(rawValue: "sendValue"), object: nil)
//事件,此時secLabel是用來顯示通知傳遞來的值,此不在贅述
func notificationValue(_ notification:Notification) {
secLabel.text = notification.object as! String?
}
接下來在第二個界面中發(fā)送通知即可。
NotificationCenter.default.post(name: NSNotification.Name.init("sendValue"), object: "我是傳遞過來的值")
注意:通知使用的一個好習(xí)慣,隨時移除他,在第一個界面移除通知:
deinit {
print("deinit \(String.init(describing: self.classForCoder))")
NotificationCenter.default.removeObserver(self)
}
閉包傳值
閉包其實和oc中的block是一個差不多的語法。理解block對于理解Closure有更好的思維方式。
我們在FirstVC中設(shè)置一個type:
//Closure傳值
typealias ValueClosure = (String)->Void
隨后在私有變量中提供Closure變量
var backValueClosure : ValueClosure?
//在回調(diào)事件中傳值
if self.backValueClosure != nil {
self.backValueClosure!("閉包傳遞來的值")
}
此時在根視圖中進行解析:
//從這個視圖中即可得到值
otherPage.backValueClosure = {(bacString:String)-> Void in
self.thidLabel.text = bacString
}
總結(jié):以上幾種方式是iOS常見的頁面?zhèn)髦敌问剑?dāng)然還可能有其他傳值(UserDefaults 單例等),但是在日常開發(fā)有這些傳值應(yīng)該就可以解決大部分的問題。我們需要注意的是,通知,回調(diào),代理傳值都有其中的利弊,以前有很多文章已經(jīng)談到,在此不再贅述,主要是界面的回傳,順傳的話,直接設(shè)置變量即可。