Create NavBar programmatically with Button and Title Swift

人走茶凉 提交于 2019-12-03 05:40:44

问题


I try to create a NavBar, so far the NavBar is no problem but if i try to add buttons and the title i get sucked.

My NavBar look like

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)

so i try to set my NavBar title like

navigationBar.topItem.title = "some title"
or
navigationBar.title = "some title"

but both fail.
Also if i try to set a button

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

this does not give me a error but the button is simply not displayed


回答1:


Updated for Swift 4

You must create a navigation item instance and set title and right/left buttons to it. After navigation item is configured add it to the navigation bar.

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)



回答2:


Basically azimov's answer in 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

}


来源:https://stackoverflow.com/questions/33717698/create-navbar-programmatically-with-button-and-title-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!