我有一个我为ViewController设置的自定义导航栏。问题是导航栏太小,我无法改变它的高度。
class AddGameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Color.lightGrey
self.setNavigationBar()
}
func setNavigationBar() {
let screenSize: CGRect = UIScreen.main.bounds
let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: 50))
let navItem = UINavigationItem(title: "Create Game")
let doneItem = UIBarButtonItem(image: UIImage(named: "Cancel"), style: .plain, target: self, action: #selector(cancelGameCreation))
navItem.leftBarButtonItem = doneItem
navBar.setItems([navItem], animated: false)
self.view.addSubview(navBar)
}
@objc func cancelGameCreation() {
dismiss(animated: true, completion: nil)
}
}
答案 0 :(得分:1)
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.lightGray
self.setNavigationBar()
}
func setNavigationBar() {
let navBar = UINavigationBar()
navBar.translatesAutoresizingMaskIntoConstraints = false
let navItem = UINavigationItem(title: "Create Game")
let doneItem = UIBarButtonItem(image: UIImage(named: "Cancel"), style: .plain, target: self, action: #selector(cancelGameCreation))
navItem.leftBarButtonItem = doneItem
navBar.setItems([navItem], animated: false)
self.view.addSubview(navBar)
if #available(iOS 11, *) {
let guide = view.safeAreaLayoutGuide
navBar.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
} else {
navBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
}
navBar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
navBar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
navBar.heightAnchor.constraint(equalToConstant: 600).isActive = true
}
@objc func cancelGameCreation() {
dismiss(animated: true, completion: nil)
}
}
使用锚点,您可以将您创建的导航功能固定在状态栏的底部,如上面Tommi所示。
话虽如此,我在上面显示的设计中看不到太多,无法通过调整导航控制器上导航栏的外观来处理。您是否有理由建立自己的导航栏而不是将视图控制器添加到导航控制器并在该导航栏上设置栏按钮项和标题。导航控制器应该处理您为您看到的约束问题。
假设视图控制器被添加到导航控制器的一个简单示例将是这样的:(只是一个想法,希望这有帮助)
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.lightGray
navigationItem.title = "Create Game"
let doneItem = UIBarButtonItem(image: UIImage(named: "Cancel"), style: .plain, target: self, action: #selector(cancelGameCreation))
navigationItem.setLeftBarButton(doneItem, animated: false)
navigationController?.navigationBar.barTintColor = UIColor.blue
}
@objc func cancelGameCreation() {
dismiss(animated: true, completion: nil)
}
}
答案 1 :(得分:0)
导航栏具有固定高度。您似乎将它放在状态栏的顶部。尝试使用约束将导航栏的顶部固定到状态栏的底部。