Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

Como criar um UIViewController no iOS: Guia Completo

O UIViewController é uma das classes fundamentais no desenvolvimento de aplicativos iOS. Ele gerencia uma tela do aplicativo e é responsável por lidar com a interface do usuário e a lógica associada. Entender como criar e utilizar UIViewControllers é essencial para qualquer desenvolvedor iOS, pois permite a construção de interfaces dinâmicas e interativas. Este artigo abordará os conceitos básicos e fornecerá exemplos práticos de como criar e configurar um UIViewController no ambiente Apple.

Exemplos:

  1. Criando um UIViewController Simples:
import UIKit

class SimpleViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Configurando a cor de fundo da view
        self.view.backgroundColor = UIColor.white

        // Criando um UILabel
        let label = UILabel()
        label.text = "Hello, UIViewController!"
        label.textAlignment = .center
        label.translatesAutoresizingMaskIntoConstraints = false

        // Adicionando o UILabel à view
        self.view.addSubview(label)

        // Configurando Auto Layout para o UILabel
        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            label.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
        ])
    }
}
  1. Apresentando um UIViewController a partir de outro UIViewController:
import UIKit

class MainViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Configurando a cor de fundo da view
        self.view.backgroundColor = UIColor.white

        // Criando um UIButton
        let button = UIButton(type: .system)
        button.setTitle("Show Detail", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(showDetail), for: .touchUpInside)

        // Adicionando o UIButton à view
        self.view.addSubview(button)

        // Configurando Auto Layout para o UIButton
        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
        ])
    }

    @objc func showDetail() {
        let detailViewController = SimpleViewController()
        self.present(detailViewController, animated: true, completion: nil)
    }
}
  1. Navegando entre UIViewControllers usando UINavigationController:
import UIKit

class FirstViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Configurando a cor de fundo da view
        self.view.backgroundColor = UIColor.white

        // Criando um UIButton
        let button = UIButton(type: .system)
        button.setTitle("Go to Second View", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(goToSecondView), for: .touchUpInside)

        // Adicionando o UIButton à view
        self.view.addSubview(button)

        // Configurando Auto Layout para o UIButton
        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
        ])
    }

    @objc func goToSecondView() {
        let secondViewController = SecondViewController()
        self.navigationController?.pushViewController(secondViewController, animated: true)
    }
}

class SecondViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Configurando a cor de fundo da view
        self.view.backgroundColor = UIColor.lightGray

        // Criando um UILabel
        let label = UILabel()
        label.text = "Second View Controller"
        label.textAlignment = .center
        label.translatesAutoresizingMaskIntoConstraints = false

        // Adicionando o UILabel à view
        self.view.addSubview(label)

        // Configurando Auto Layout para o UILabel
        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            label.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
        ])
    }
}

Para utilizar o UINavigationController, você deve configurá-lo no AppDelegate ou na SceneDelegate:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)

        let firstViewController = FirstViewController()
        let navigationController = UINavigationController(rootViewController: firstViewController)

        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()

        return true
    }
}

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.