Swift Unwind 使用說明 segue

Swift Unwind 使用說明 segue

swift unwind 使用說明

文中 VC = ViewController

當從子 VC 返回的時候,就會用到 unwind,會自動找尋其父 VC 進行跳轉。swift

好比:app

  1. 有一個 TemeperatureTableViewController 是個溫度列表,是根 VC
  2. 有一個輸入溫度的子 VC AddTemperatureViewController 用於輸入溫度
  3. 如今添加 unwind 相關方法,並實現點擊確認的時候關閉 AddTemperatureViewController 並修改 TemeperatureTableViewController 的標題爲 AddTemperatureViewController 中輸入的內容

實現步驟

1) 在上游 vc 中添加 unwind 方法

在根VC TemeperatureTableViewController 中輸入 unwind 就會自動生成下面的代碼,一個包含 UIStoryboardSegue做爲參數的方法async

create-unwind.png

@IBAction func unwindToTableViewController(_ unwindSegue: UIStoryboardSegue) {
    // 這裏面寫從子VC返回時要作的事,這裏能夠獲取到子VC的數據
    if let svc = unwindSegue.source as? AddTemperatureViewController{
        self.navigationItem.title =  svc.textField.text
    }
}

2) storyBoard 鏈接 exit 生成 unwindSegue

右擊 AddTemperatureViewController 的圖標拖動到 Exit 上就會顯示 根VC
TemeperatureTableViewController 中的 unwindToTableViewController 方法ide

segue-create.png
segue-select.png

3) 添加 identifier

點擊 左側 Exit 下文多出的 segue,在右側面板中添加 identifier spa

add-identifier.png

4) 在 AddTemperatureViewController 調用這個 segue

performSegue(withIdentifier: "unwindToTVC", sender: self)

此時就會觸發 TemeperatureTableViewController 中的 unwindToTableViewController 方法3d

效果

以前code

origin.png

以後 orm

after.png

代碼

TemeperatureTableViewController.swift對象

//
//  TemperatureTableViewController.swift
//  BodyTemparature
//
//  Created by Kyle on 2020/2/10.
//  Copyright © 2020 Cyan Maple. All rights reserved.
//

import UIKit
import HealthKit

/// 獲取 Health 中的體溫數據
class TemperatureTableViewController: UITableViewController {
        
    // 存儲查詢到的數據
    private var temperatureSamples: Array<HKSample> = []
    
    
    private var kit: HKHealthStore! {
        return HKHealthStore()
    }
    
    private let queryType = HKQuantityType.quantityType(forIdentifier: .bodyTemperature)!
    private let querySample = HKSampleType.quantityType(forIdentifier: .bodyTemperature)!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        navigationItem.title = "體溫記錄 top 10"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add",
                                                            style: .plain,
                                                            target: self,
                                                            action: #selector(buttonPressed))
        
        
        // 若是 iOS 11+ 顯示大標題
        if #available(iOS 11.0, *) {
            self.navigationController?.navigationBar.prefersLargeTitles = true
        }
        
        
        if HKHealthStore.isHealthDataAvailable(){
            //  Write Authorize
            let queryTypeArray: Set<HKSampleType> = [queryType]
            //  Read Authorize
            let querySampleArray: Set<HKObjectType> = [querySample]
            kit.requestAuthorization(toShare: queryTypeArray, read: querySampleArray) { (success, error) in
                if success{
                    self.getTemperatureData()
                } else {
                    self.showAlert(title: "Fail", message: "Unable to access to Health App", buttonTitle: "OK")
                }
            }
        } else {
            // show alert
            showAlert(title: "Fail", message: "設備不支持使用健康", buttonTitle: "退出")
        }
    }
    
    
    @objc func buttonPressed() {
        performSegue(withIdentifier: "AddTemperature", sender: self)
    }
    
    
    
    func getTemperatureData(){
        
        /*
        // 時間查詢條件對象
        let calendar = Calendar.current
        let todayStart =  calendar.date(from: calendar.dateComponents([.year,.month,.day], from: Date()))
        let dayPredicate = HKQuery.predicateForSamples(withStart: todayStart,
                                                       end: Date(timeInterval: 24*60*60,since: todayStart!),
                                                       options: HKQueryOptions.strictStartDate) */

        // 建立查詢對象
        let temperatureSampleQuery = HKSampleQuery(sampleType: querySample, // 要獲取的類型對象
                                                   predicate: nil, // 時間參數,爲空時則不限制時間
                                                   limit: 10, // 獲取數量
                                                   sortDescriptors: [NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)]) // 獲取到的數據排序方式
        { (query, results, error) in
            /// 獲取到結果以後 results 是返回的 [HKSample]?
            if let samples = results {
                // 挨個插入到 tableView 中
                for sample in samples {
                    DispatchQueue.main.async {
                        self.temperatureSamples.append(sample)
                        self.tableView.insertRows(at: [IndexPath(row: self.temperatureSamples.firstIndex(of: sample)!, section:0)],
                                                  with: .right   )
                    }
                }
            }
        }

        // 執行查詢操做
        kit.execute(temperatureSampleQuery)
    }
    
    
    /// 自定義方法:輸入 HKSample 輸出 日期和溫度
    func getTemperatureAndDate(sample: HKSample) -> (Date, Double) {
        let quantitySample = sample as! HKQuantitySample
        let date = sample.startDate
        let temperature = quantitySample.quantity.doubleValue(for: .degreeCelsius())
        return (date, temperature)
    }
        
    // MARK: - Table view data source
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return temperatureSamples.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TemperatureCell", for: indexPath)
        let (date, temperature) = getTemperatureAndDate(sample: temperatureSamples[indexPath.row])
        cell.textLabel?.text = String(temperature)
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium
        dateFormatter.timeStyle = .short
        dateFormatter.locale = Locale(identifier: "zh_CN")
        
        cell.detailTextLabel?.text = dateFormatter.string(from: date)
        return cell
    }
    
    // MARK: - Tool Methods - Alert
    func showAlert(title: String, message: String, buttonTitle: String) {
        let alert = UIAlertController(title: title,
                                      message: message,
                                      preferredStyle: .alert)
        let okAction = UIAlertAction(title: buttonTitle, style: .default, handler: { (action) in
        })
        alert.addAction(okAction)
        DispatchQueue.main.async {
            self.present(alert, animated: true, completion: nil)
        }
    }
    
    @IBAction func unwindToTableViewController(_ unwindSegue: UIStoryboardSegue) {
        if let svc = unwindSegue.source as? AddTemperatureViewController{
            self.navigationItem.title =  svc.textField.text
        }
    }
    
}

AddTemperatureViewController.swiftblog

//
//  AddTemperatureViewController.swift
//  BodyTemparature
//
//  Created by Kyle on 2020/2/14.
//  Copyright © 2020 Cyan Maple. All rights reserved.
//

import UIKit

class AddTemperatureViewController: UIViewController, UITextFieldDelegate {
    

    @IBOutlet weak var textField: UITextField!
    
    override func viewWillAppear(_ animated: Bool) {
        textField.becomeFirstResponder()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
        
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if let text = textField.text {
            if let temperature = Double(text) {
                print(String(describing: temperature))
                self.dismiss(animated: true, completion: nil)
                performSegue(withIdentifier: "unwindToTVC", sender: self)
            }
        }
    }
    
    // MARK: - Navigation
    
    
}
相關文章
相關標籤/搜索