我尝试创建一个NavBar,到目前为止NavBar没有问题,但如果我尝试添加按钮和标题,我会被吸。
我的NavBar看起来像
let NameHeight = screenHeight * 0.09
let NameWidth = screenWidth
let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: NameWidth, height: NameHeight))
self.view.addSubview(navBar)
所以我尝试将我的NavBar标题设置为
navigationBar.topItem.title = "some title"
or
navigationBar.title = "some title"
但都失败了 此外,如果我尝试设置按钮
let btnName = UIButton()
btnName.setImage(UIImage(named: "imagename"), forState: .Normal)
btnName.frame = CGRectMake(0, 0, 30, 30)
btnName.addTarget(self, action: Selector("action"), forControlEvents: .TouchUpInside)
//.... Set Right/Left Bar Button item
let rightBarButton = UIBarButtonItem()
rightBarButton.customView = btnName
self.navigationItem.rightBarButtonItem = rightBarButton
这不会给我一个错误,但按钮根本不显示
答案 0 :(得分:43)
更新了Swift 4
您必须创建导航项目实例并为其设置标题和向右/向左按钮。配置导航项后,将其添加到导航栏。
let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: 320, height: 44))
view.addSubview(navBar)
let navItem = UINavigationItem(title: "SomeTitle")
let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: nil, action: #selector(selectorName:))
navItem.rightBarButtonItem = doneItem
navBar.setItems([navItem], animated: false)
答案 1 :(得分:30)
基本上azimov在 Swift 4
中的回答override func viewDidLoad() {
super.viewDidLoad()
self.setNavigationBar()
}
func setNavigationBar() {
let screenSize: CGRect = UIScreen.main.bounds
let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: 44))
let navItem = UINavigationItem(title: "")
let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: nil, action: #selector(done))
navItem.rightBarButtonItem = doneItem
navBar.setItems([navItem], animated: false)
self.view.addSubview(navBar)
}
@objc func done() { // remove @objc for Swift 3
}