swift中UINavigationController的使用

2016-12-20  本文已影响0人  不安分心

UINavigationController的使用

1.AppDelegate中
var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        // 创建window
        self.window = UIWindow(frame: UIScreen.main.bounds)
        // 创建UINavigationController
        let rootVC = RootViewController()
        let nav = UINavigationController(rootViewController: rootVC)
        
        self.window?.rootViewController = nav
        self.window?.makeKeyAndVisible()
        return true
    }

2. RootViewController中
import UIKit

class RootViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.red

        self.setupNav()
    }
    
    func setupNav() {
        self.title = "首页"
        // 创建只带标题的UIBarButtonItem
        let nextItem = UIBarButtonItem(title: "next", style: .plain, target: self, action: #selector(nextPage));
        self.navigationItem.rightBarButtonItem = nextItem
    
    }
    func nextPage() {
        print("nextPage")
        let vc = MainViewController()
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
}

3.MainViewController中
import UIKit

class MainViewController: UIViewController {

    var btn: UIButton?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.orange
        btn = UIButton(type: .contactAdd)
        btn?.addTarget(self, action: #selector(back), for: .touchUpInside)

        self.setupNav()
    }
    func setupNav() {
        self.title = "第二页"
        // 创建带图片的UIBarButtonItem
//        let image = UIImage(named: "ico_fanhui_")
//        let popItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(back))
//        let pop = UIBarButtonItem(image: image, landscapeImagePhone: image, style: .plain, target: self, action: #selector(back))
        // 创建自定义的UIBarButtonItem
        let btnItem = UIBarButtonItem(customView: btn!)
        self.navigationItem.leftBarButtonItem = btnItem
    }
    func back() {
        /** 
         该方法在Xcode 8 / Swift 3下会报警告: “Expression of type UIViewController? is unused” warning
         在swift3下   popViewController(animated:) 返回returns UIViewController?,而UIViewController?没有使用,所以报警告
        */
//        self.navigationController?.popViewController(animated: true)
        // 下面两种写法一样
        // _的作用,忽略返回值,起忽略作用
        _ = navigationController?.popViewController(animated: true)
        _ = self.navigationController?.popViewController(animated: true)
        
    }
}
上一篇下一篇

猜你喜欢

热点阅读