iOS*_*nee 14 uinavigationbar uiviewcontroller uinavigationcontroller ios swift
我对swift和iOS相对较新,无法找到答案或帮助解决我的问题.我想在单击上一个视图中的按钮时创建导航控制器视图.我之前的观点是在最后一页上有一个按钮.我成功地将按钮连接到我的下一个视图,但我无法使视图像导航控制器一样.例如,当显示导航栏时,我无法向其添加导航项.
所以我的问题是:有没有办法设置我创建的新视图,方法是在第一个视图中单击我的按钮作为导航视图的根控制器?
我的代码的简短版本:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: view.frame.width / 2, y: view.frame.height / 2, width: 40, height: 40))
button.backgroundColor = .red
button.tintColor = .white
button.setTitle("Test", for: .normal)
button.addTarget(self, action: #selector(change), for: .touchUpInside)
view.addSubview(button)
}
func change () {
let otherView = SecondViewController()
self.present(otherView, animated: true, completion: nil)
}
}
class SecondViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
}
}
Run Code Online (Sandbox Code Playgroud)
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: view.frame.width / 2, y: view.frame.height / 2, width: 40, height: 40))
button.backgroundColor = .red
button.tintColor = .white
button.setTitle("Test", for: .normal)
button.addTarget(self, action: #selector(change), for: .touchUpInside)
view.addSubview(button)
}
func change () {
let otherView = SecondViewController()
self.present(otherView, animated: true, completion: nil)
}
}
class SecondViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
}
}
Run Code Online (Sandbox Code Playgroud)
}
SecondViewController得到了导航栏显示,但我有实现导航项的问题,因为它们没有显示.
我提供的第二个视图控制器是否必须是UIViewController或UINavigationController类型?
我知道,有更简单的方法可以通过使用故事板来实现我的目标,但在我看来,我通过代码创建自己的引用而不是通过将它们拖出故事板来创建它们来更好地理解它.
编辑:我现在没有客观的背景和学习快速约4周.我感谢任何帮助.
VRA*_*ome 44
你可以添加UINavigationController如下:
首先你必须创建对象SecondViewController,
let objVC: SecondViewController? = storyboard?.instantiateViewController(withIdentifier: "SecondViewController")
Run Code Online (Sandbox Code Playgroud)
要么
let objVC: SecondViewController? = SecondViewController(nibName: "SecondViewController", bundle: nil)
Run Code Online (Sandbox Code Playgroud)
要么
let objVC: SecondViewController? = SecondViewController()
Run Code Online (Sandbox Code Playgroud)
然后添加导航到 SecondViewController
let aObjNavi = UINavigationController(rootViewController: objVC!)
Run Code Online (Sandbox Code Playgroud)
如果你想出席然后使用:
self.present(aObjNavi, animated: true) {
}
Run Code Online (Sandbox Code Playgroud)
如果你想推,那么使用:
self.navigationController?.pushViewController(aObjNavi, animated: true)
Run Code Online (Sandbox Code Playgroud)
如果要设置为根控制器,请使用:
let appDelegate: AppDelegate = (UIApplication.shared.delegate as? AppDelegate)!
appDelegate.window?.rootViewController = aObjNavi
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41137 次 |
| 最近记录: |