Swift - 导航条(UINavigationBar)的使用

与导航控制器(UINavigationController)同时实现导航条和页面切换功能不同。
导航条(UINavgationBar)可以单独使用,添加至任何的UIView中。UINavigationBar比较重要的属性为,左侧按钮,中间的标题,以及右侧按钮。

下面是一个使用样例,点击左侧加号会添加一个新的导航项,点击右侧Cancel会移除当前最上层导航项。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import UIKit
 
class ViewController: UIViewController {
     
    var count = 0
    //声明导航条
    var navigationBar:UINavigationBar?
 
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //实例化导航条
        navigationBar = UINavigationBar(frame: CGRectMake(0, 20, 320, 44))
        self.view.addSubview(navigationBar!)
        onAdd()
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
     
    //增加导航项函数
    func onAdd(){
        count++
        //给导航条增加导航项
        navigationBar?.pushNavigationItem(onMakeNavitem(), animated: true)
    }
     
    //删除导航项函数
    func onRemove(){
        if count > 1{
            //减少导航项数量
            count--
            //从导航条中移除最后一个导航项
            navigationBar?.popNavigationItemAnimated(true)
        }
    }
     
    //创建一个导航项
    func onMakeNavitem()->UINavigationItem{
        var navigationItem = UINavigationItem()
        //创建左边按钮
        var leftBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add,
            target: self, action: "onAdd")
        //创建右边按钮
        var rightBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel,
            target: self, action: "onRemove")
        //设置导航栏标题
        navigationItem.title = "第\(count)个导航项"
        //设置导航项左边的按钮
        navigationItem.setLeftBarButtonItem(leftBtn, animated: true)
        //设置导航项右边的按钮
        navigationItem.setRightBarButtonItem(rightBtn, animated: true)
        return navigationItem
    }
}
posted @   brave-sailor  阅读(1869)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2014-09-25 Android 出现警告Exported service does not require permission
2013-09-25 Android中的JSON详细总结
点击右上角即可分享
微信分享提示