簡體   English   中英

如何讓 Swift 在 Seguing 后記住 UIImage 顏色

[英]How to let Swift remember UIImage colours after seguing

我剛剛開始學習 Swift,我正在構建一個簡單的應用程序。 主頁只是一個表格:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let theData: [String] = ["BRDA", "HFH", "ENGRII", "HSSB", "GRVT"]
    let cellReuseIdentifier = "cell"

    @IBOutlet weak var tableView: UITableView!
    @IBAction func unwindToHome(segue: UIStoryboardSegue) { }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.frame = CGRect(x: 0, y: 200, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height-600)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

        self.view.addSubview(tableView)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return theData.count
    }

    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
        cell.textLabel?.text = theData[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (indexPath.row == 0) {
            // segue to BRDA
            performSegue(withIdentifier: "toBRDA", sender: nil)
        } else {
            print("Will add later! You clicked on \(theData[indexPath.row]).")
        }
    }
}

我將第一個條目設為可點擊,然后將其轉至另一個控制器。 這個新控制器有一個 UIImage 對象,當你點擊它時它會改變顏色。

class BRDAController: UIViewController {

    @IBOutlet weak var thePic: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        var tapGesture = UITapGestureRecognizer()
        tapGesture = UITapGestureRecognizer(target: self, action: #selector(BRDAController.didTap(_:)))
        tapGesture.numberOfTapsRequired = 1
        tapGesture.numberOfTouchesRequired = 1
        thePic.addGestureRecognizer(tapGesture)
        thePic.isUserInteractionEnabled = true
        thePic.backgroundColor = UIColor.yellow
        // Do any additional setup after loading the view.
    }

    @objc func didTap(_ sender: UITapGestureRecognizer) {
        // User tapped at the point above. Do something with that if you want.
        if thePic.backgroundColor == UIColor.yellow {
            thePic.backgroundColor = UIColor.green
        } else {
            thePic.backgroundColor = UIColor.yellow
        }
    }

    @IBAction func backButton(_ sender: Any) {
        self.performSegue(withIdentifier: "goBackHome", sender: nil)
    }
}

我使用了一個展開轉場回到我的家,但是當我回到另一個控制器時,狀態已被重置(顏色已設置為其默認黃色)。 我如何讓我的代碼“記住”它以前的狀態?

這取決於用例。 如果要保存數據...

  • ...退出並重新啟動應用程序后,將其保存為用戶默認值
  • ...僅會話,返回上一個 VC 時,使用委托方法

會話之外: UserDefaults

@IBAction func backButton(_ sender: Any) {
    UserDefaults.standard.set(thePic.backgroundColor, forKey: "color")
}

...使用此處的 UserDefaults 擴展。

下次啟動應用程序時,請像這樣讀取顏色:

let color = UserDefaults.standard.color(forKey: "color")

僅會話:委托方法

創建委托協議:

protocol BRDAControllerDelegate: class {
    func brdaController(_ brdaController: BRDAController, willDismissPassing data: [String: Any])
}

然后,創建一個委托屬性:

class BRDAController: UIViewController {
    weak var delegate: BRDAControllerDelegate?

在解散之前,通知代表:

    @IBAction func backButton(_ sender: Any) {
        delegate?.brdaController(self, willDismissPassing: ["color": thePic.backgroundColor])
        // dismiss here
    }
}

在呈現視圖控制器中,從委托方法繼承:

class ViewController: ..., BRDAControllerDelegate {
    func brdaController(_ brdaController: BRDAController, willDismissPassing data: [String: Any]) {
        if let color = data["color"] as? UIColor {
            // do something with your color here
        }
    }

並在轉換之前將委托設置為self

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)
    if let brdaVC = segue.destination as? BRDAController {
        brdaVC.delegate = self
    }
}

另外,我建議你關閉你的視圖控制器,而不是創建一個新的轉回:

@IBAction func backButton(_ sender: Any) {
    // embedded in navigation controller? use:
    navigationController?.popViewController(animated: true)
    // OR, no navigation controller? use:
    dismiss(animated: true)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM