- Xcode 8.3.3
- Swift 3.1
ある程度Xcode側で用意されてるので、それを利用するだけなので😅
ただし細かい調整したい場合は元クラスを調べる等、調査が必要ですので適宜Jump to definitionしましょう🙆
動作としてExample1のナビの右上NextをタップするとExample2へ遷移。
Example2ではナビの左上BackをタップでExample1へ戻れるようにします。
import UIKit
class Example1ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Example1"
self.navigationItem.leftBarButtonItem = nil
let btnRight = UIBarButtonItem(title: "Next >", style: UIBarButtonItemStyle.plain, target: self, action: #selector(Example1ViewController.goNext))
self.navigationItem.rightBarButtonItem = btnRight
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc func goNext() {
self.navigationController?.pushViewController(Example2ViewController(), animated: true)
}
}</textarea><br />
<br />
<textarea class="code">import UIKit
class Example2ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Example2"
let btnLeft = UIBarButtonItem(title: "< Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(Example2ViewController.goBack))
self.navigationItem.leftBarButtonItem = btnLeft
self.navigationItem.rightBarButtonItem = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc func goBack() {
self.navigationController?.popViewController(animated: true)
}
}
使わないleftBarButtonItemやrightBarButtonItemをnilしなくても設定しなければ何も表示されませんが、今後の事も考えると初期化(あえて非表示してますよアピール)しておきましょう。
また、通常こんなハードコーディングをすることはありません。
例としてあえてnil設定を記述したのは、条件によってnilしたりアイテム設定したりというのが書きやすいようにです😀
abstractみたい(Swiftではprotocol extensionか?)にして他メソッドで設定するのも良いですし🙌
最後にこのViewControllerを呼出しましょう。
let example1 = UINavigationController(rootViewController: Example1ViewController()) self.present(example1, animated: true, completion: nil)
0 件のコメント:
コメントを投稿