作者:Tomasz Szulc,原文鏈接类溢,原文日期:2015-12-6
譯者:靛青K凌蔬;校對(duì):Channe;定稿:Cee
這是一個(gè)不使用 delegate 模式傳遞回調(diào)數(shù)據(jù)的好方法闯冷。
我今天注意到這個(gè)小技巧砂心,值得和你分享一下。
通常當(dāng)我們創(chuàng)建一個(gè)視圖控制器作為 picker 時(shí)蛇耀,它會(huì)從屏幕的底部出現(xiàn)辩诞,覆蓋在當(dāng)前頁(yè)面上,并且僅只占屏幕的一部分纺涤。當(dāng)選擇一個(gè)值后译暂,就通過(guò) delegate 模式返回回來(lái)。代碼大概就像這樣:
class ViewController: UIViewController, AnimalPickerViewControllerDelegate {
@IBOutlet var label: UILabel!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowAnimalPicker" {
let pickerVC = segue.destinationViewController as! AnimalPickerViewController
pickerVC.delegate = self
}
}
func animalPicker(picker: AnimalPickerViewController, didSelectAnimal animal: String) {
label.text = animal
}
}
protocol AnimalPickerViewControllerDelegate: class {
func animalPicker(picker: AnimalPickerViewController, didSelectAnimal animal: String)
}
class AnimalPickerViewController: UIViewController {
weak var delegate: AnimalPickerViewControllerDelegate?
@IBAction func dogButtonPressed(sender: AnyObject) {
selectAnimal("Dog")
}
@IBAction func catButtonPressed(sender: AnyObject) {
selectAnimal("Cat")
}
@IBAction func snakeButtonPressed(sender: AnyObject) {
selectAnimal("Snake")
}
private func selectAnimal(animal: String) {
delegate?.animalPicker(self, didSelectAnimal: animal)
dismissViewControllerAnimated(true, completion: nil)
}
}
于是就像你看到的洒琢,我使用了 segue 去彈出這個(gè) picker 視圖控制器,但我使用了 delegate 模式獲取返回的數(shù)據(jù)值褐桌。
今天我認(rèn)識(shí)到在這種情況下衰抑,使用 unwind segue 更合適。我沒(méi)有必要使用 delegate 模式荧嵌。并且代碼是這個(gè)樣子:
class ViewController: UIViewController {
@IBOutlet var label: UILabel!
@IBAction func performUnwindSegue(segue: UIStoryboardSegue) {
if segue.identifier == AnimalPickerViewController.UnwindSegue {
label.text = (segue.sourceViewController as! AnimalPickerViewController).selectedAnimal
}
}
}
class AnimalPickerViewController: UIViewController {
static let UnwindSegue = "UnwindAnimalPicker"
private(set) var selectedAnimal: String!
@IBAction func dogButtonPressed(sender: AnyObject) {
selectAnimal("Dog")
}
@IBAction func catButtonPressed(sender: AnyObject) {
selectAnimal("Cat")
}
@IBAction func snakeButtonPressed(sender: AnyObject) {
selectAnimal("Snake")
}
private func selectAnimal(animal: String) {
selectedAnimal = animal
performSegueWithIdentifier(AnimalPickerViewController.UnwindSegue, sender: nil)
}
是不是更好一些呛踊?對(duì)于我來(lái)說(shuō)砾淌,在這種特別的情況時(shí),的確更好谭网。希望對(duì)你有一些幫助汪厨!
(譯者注:關(guān)于 Unwind Segue 的使用,需要注意的幾點(diǎn)愉择。我們最好先將下面的代碼寫(xiě)上:
@IBAction func performUnwindSegue(segue: UIStoryboardSegue) {
if segue.identifier == AnimalPickerViewController.UnwindSegue {
label.text = (segue.sourceViewController as! AnimalPickerViewController).selectedAnimal
}
}
這樣我們?cè)購(gòu)?button 等控件拉向 exit 時(shí)才會(huì)有效果劫乱。至于 identifier 是設(shè)置在剛剛拉向 exit 的 segue(unwind segue)。我補(bǔ)寫(xiě)了本文的 demo锥涕,如果你還有什么困惑可以直接看這個(gè) demo衷戈。)
本文由 SwiftGG 翻譯組翻譯,已經(jīng)獲得作者翻譯授權(quán)层坠,最新文章請(qǐng)?jiān)L問(wèn) http://swift.gg殖妇。