使用Button和Title Swift以编程方式创建NavBar [英] Create NavBar programmatically with Button and Title Swift

查看:97
本文介绍了使用Button和Title Swift以编程方式创建NavBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建NavBar,到目前为止,NavBar没问题,但是当我尝试添加按钮和标题时,它们不会显示

I try to create a NavBar, so far the NavBar is no problem but when I try to add the buttons and title, they don't get displayed

我的NavBar看起来像

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)

所以我尝试将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

推荐答案

已针对Swift 5更新

创建一个导航项目实例,并为其设置标题和向右/向左按钮.配置导航项后,将其添加到导航栏中.

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: view.frame.size.width, height: 44))
view.addSubview(navBar)

let navItem = UINavigationItem(title: "SomeTitle")
let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(selectorName:))
navItem.rightBarButtonItem = doneItem

navBar.setItems([navItem], animated: false)

这篇关于使用Button和Title Swift以编程方式创建NavBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆