iOS自定义NavigationBar
时间: 2023-12-17 13:06:29 浏览: 86
iOS自定义导航栏
在iOS中,可以通过以下方式自定义NavigationBar:
1. 设置NavigationBar的背景色和透明度
```swift
// 设置NavigationBar的背景色
navigationController?.navigationBar.barTintColor = UIColor.red
// 设置NavigationBar的透明度
navigationController?.navigationBar.isTranslucent = true
```
2. 设置NavigationBar的标题和字体样式
```swift
// 设置NavigationBar的标题
navigationItem.title = "Custom Title"
// 设置NavigationBar的字体样式
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.white]
```
3. 设置NavigationBar的返回按钮和图片
```swift
// 设置NavigationBar的返回按钮
let backButton = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButton
// 设置NavigationBar的返回图片
let backImage = UIImage(named: "back")
navigationController?.navigationBar.backIndicatorImage = backImage
navigationController?.navigationBar.backIndicatorTransitionMaskImage = backImage
```
4. 隐藏NavigationBar
```swift
// 隐藏NavigationBar
navigationController?.navigationBar.isHidden = true
```
5. 自定义NavigationBar的左右按钮
```swift
// 自定义NavigationBar的左按钮
let leftButton = UIBarButtonItem(title: "Left", style: .plain, target: self, action: #selector(leftButtonTapped))
navigationItem.leftBarButtonItem = leftButton
// 自定义NavigationBar的右按钮
let rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(rightButtonTapped))
navigationItem.rightBarButtonItem = rightButton
// 左按钮点击事件
@objc func leftButtonTapped() {
// do something
}
// 右按钮点击事件
@objc func rightButtonTapped() {
// do something
}
```
阅读全文