-5

I'm new to swift, so wanted to ask, how to move from one view controller to another without a button, but with label. For example if label is "bluhbluh" then it moves to second view controller. Thanks!

Adley
  • 9
  • 1
  • 2
    You could set an observer for the label's text and if the text matches what you're looking for, the observer would call an action that performs the segue. http://stackoverflow.com/a/28395000/4475605 – Adrian Jan 18 '17 at 18:31
  • You could to create a segue with an identifier on Interface builder from one view controller to the other. Then, in your code you should create a condition, for example on viewDidLoad, that check if label text = "bluhbluh" and it that is true, you perform that segue with the identifier. Anyways, it would help more to see what you want to achieve, since having a label for a transition between scenes sounds weird, at least for me, would make more sense to transition to other if the user taps something on a text field instead of a label condition. But thats because I don't know what you want. – Mago Nicolas Palacios Jan 18 '17 at 18:42
  • @Adrian He is talking about a label... I also think that a text field makes more sense, but thats what he is asking. – Mago Nicolas Palacios Jan 18 '17 at 18:44
  • I agree with one comment here - why? It's not intuitive, not user-expected, not even developer expected. Besides, why not just make a UIButton, which **has** a label in it, **look** like a label? –  Jan 18 '17 at 18:58

1 Answers1

1

As others have mentioned, this is probably not a good pattern to follow. But to answer your question, you could try something like this.

import UIKit

class FirstViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        label.addObserver(self,
                          forKeyPath: "text",
                          options: [.new, .old],
                          context: nil)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "text" {
            if label.text == "Text that triggers navigation" {
                let secondVC = SecondViewController()
                navigationController?.pushViewController(secondVC, animated: true)
            }
        }
    }

}

class SecondViewController: UIViewController {}
Mike Cole
  • 1,291
  • 11
  • 19