欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

代码示例:添加按键使得可以从当前视图控制器跳到另一个

程序员文章站 2022-07-08 11:56:47
示例:rootViewController和ViewController之间的互相跳转import UIKitclass RootViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.green let button = UIButton(type:...

示例:rootViewController和ViewController之间的互相跳转

import UIKit

class RootViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.green
        
        let button = UIButton(type: .custom)
        button.frame = CGRect(x: 0, y: 200, width: UIScreen.main.bounds.width, height: 50)
        button.backgroundColor = UIColor.white
        button.setTitle("打开新的视图控制器", for: .normal)
        button.setTitleColor(UIColor.gray, for: .normal)
        view.addSubview(button)
        button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
    }

    func buttonClick() {
        navigationController?.pushViewController(ViewController(), animated: true)
        // 另一种跳转方式
        // present(ViewController(), animated: true, completion: nil)
    }

}
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.red
       
        let button = UIButton(type: .custom)
        button.frame = CGRect(x: 0, y: 200, width: UIScreen.main.bounds.width, height: 50)
        button.backgroundColor = UIColor.white
        button.setTitle("回到RootViewController", for: .normal)
        button.setTitleColor(UIColor.gray, for: .normal)
        view.addSubview(button)
        button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
    }

    func buttonClick() {
        navigationController?.popViewController(animated: true)
        // 另一种跳转方式 成对出现
        dismiss(animated: true, completion: nil)
    }
}

本文地址:https://blog.csdn.net/weixin_44337445/article/details/107374368

相关标签: iOS开发 Swift