Swift - 导航条(UINavigationBar)的使用
作者:hangge | 2015-04-17 16:02
(本文代码已升级至Swift4)
与导航控制器(UINavigationController)同时实现导航条和页面切换功能不同。
导航条(UINavgationBar)可以单独使用,添加至任何的 UIView 中。UINavigationBar 比较重要的属性为,左侧按钮,中间的标题,以及右侧按钮。
下面是一个使用样例,点击左侧加号会添加一个新的导航项,点击右侧 Cancel 会移除当前最上层导航项。


import UIKit
class ViewController: UIViewController {
var count = 0
//声明导航条
var navigationBar:UINavigationBar?
override func viewDidLoad() {
super.viewDidLoad()
//实例化导航条
navigationBar = UINavigationBar(frame: CGRect(x:0, y:20, width:320, height:44))
self.view.addSubview(navigationBar!)
onAdd()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//增加导航项函数
@objc func onAdd(){
count = count + 1
//给导航条增加导航项
navigationBar?.pushItem(onMakeNavitem(), animated: true)
}
//删除导航项函数
@objc func onRemove(){
if count > 1{
//减少导航项数量
count = count - 1
//从导航条中移除最后一个导航项
navigationBar?.popItem(animated: true)
}
}
//创建一个导航项
func onMakeNavitem()->UINavigationItem{
let navigationItem = UINavigationItem()
//创建左边按钮
let leftBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.add,
target: self, action: #selector(onAdd))
//创建右边按钮
let rightBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel,
target: self, action: #selector(onRemove))
//设置导航栏标题
navigationItem.title = "第\(count)个导航项"
//设置导航项左边的按钮
navigationItem.setLeftBarButton(leftBtn, animated: true)
//设置导航项右边的按钮
navigationItem.setRightBarButton(rightBtn, animated: true)
return navigationItem
}
}
全部评论(1)
这个感觉没啥用处
站长回复:这个只是演示下UINavigationBar的基本用法。