3.Swift导航栏的使用

Swift 导航栏的使用

一、基本使用

1.1 创建导航栏

在AppDelegate 如下方法中添加创建导航栏的代码:

swift 复制代码
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {        
    self.window?.backgroundColor = UIColor.white
    let main = ControlMainController()
    let navigation = UINavigationController(rootViewController: main)
    self.window?.rootViewController = navigation
    return true
}
1.2 导航栏上添加按钮
swift 复制代码
//添加导航栏左边按钮
let item1 = UIBarButtonItem(title: "我的", style: UIBarButtonItem.Style.plain, target: self, action: #selector(buttonClick))
self.navigationItem.leftBarButtonItem = item1

//添加导航栏右边按钮
let item2 = UIBarButtonItem(title: "设置", style: UIBarButtonItem.Style.plain, target: self, action: #selector(buttonClick))
self.navigationItem.rightBarButtonItem = item2

//添加多个按钮
let item1 = UIBarButtonItem(title: "我的", style: UIBarButtonItem.Style.plain, target: self, action: #selector(buttonClick))
let item2 = UIBarButtonItem(title: "设置", style: UIBarButtonItem.Style.plain, target: self, action: #selector(buttonClick))
self.navigationItem.rightBarButtonItems = [item1, item2]
1.3 页面跳转
swift 复制代码
//跳转到下个页面
func buttonClick(button:UIButton) {
  let secondVC = SecondViewController()
  self.navigationController?.pushViewController(secondVC, animated:true)
}
//返回上一个页面
func back() {
  self.navigationController?.popViewControllerAnimated(true)
}
相关推荐
geovindu14 分钟前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
geovindu1 小时前
python:Lasso
开发语言·后端·python·算法
Lucas. Wáng1 小时前
Linux网络编程之网络套接字
linux·服务器·网络
数字新视界1 小时前
动环智能监控在机房管理中的智能应用与安全保障
服务器·数据中心·机房·环境管理·环控系统
多加点辣也没关系2 小时前
JavaScript|第42章:安全与最佳实践
开发语言·javascript·安全
3095566662 小时前
股票数据落库前的去重与主键设计:一次 SQLite 写入实录
java·开发语言·jvm·数据库·redis·python·sqlite
进击的荆棘2 小时前
Linux网络——Socket编程TCP
linux·运维·服务器·网络·tcp/ip
大今野2 小时前
2026 专转本计算机|Linux CentOS7 软件包管理:yum 仓库配置与常用命令考点全解(附例题)
linux·运维·服务器·专转本
利威尔xu2 小时前
2026-11-19-Go反射为什么慢面试
开发语言·面试·golang
山楂树の3 小时前
Python 函数:参数、作用域、Lambda 与类型注解
开发语言·python