UIKit – UIBarButtonItem(导航按钮)
UIBarButtonItem继承于UIBarItem,用于设置导航栏上的按钮组。
1.显示与隐藏回退按钮
-
self.navigationItem.hidesBackButton = true
-
self.navigationItem.setHidesBackButton(true, animated: true)
2.创建文字按钮
-
//左侧按钮
-
let leftButton = UIBarButtonItem(title: “Back”, style: .plain, target: self, action:
-
self.navigationItem.leftBarButtonItem = leftButton
-
-
//右侧按钮
-
let rightButton = UIBarButtonItem(title: “Next”, style: .plain, target: self, action:
-
self.navigationItem.rightBarButtonItem = rightButton
3.创建系统自带按钮
-
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: nil)
-
let cameraButton = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: nil)
-
let editButton = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: nil)
-
-
//同时添加多个按钮
-
self.navigationItem.rightBarButtonItems = [addButton,cameraButton,editButton]
4.添加自定义按钮
-
//自定义搜索框
-
let search = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 25))
-
search.backgroundColor = UIColor.gray
-
search.placeholder = “请输入搜索内容”
-
search.layer.masksToBounds = true
-
search.layer.cornerRadius = 8
-
search.layer.borderWidth = 2
-
search.layer.borderColor = UIColor.blue.cgColor
-
let itemButton = UIBarButtonItem(customView: search)
-
-
//文本
-
let txt = UILabel(frame: CGRect(x: 0, y: 0, width: 40, height: 25))
-
txt.text = “搜索”
-
let txtButton = UIBarButtonItem(customView: txt)
-
-
//添加按钮组
-
self.navigationItem.rightBarButtonItems = [itemButton, txtButton]
5.按钮样式
-
let leftButton = UIBarButtonItem(title: “Back”, style: .plain, target: self, action:
-
//字体颜色
-
leftButton.tintColor = UIColor.red
-
//按钮背景图片
-
leftButton.setBackgroundImage(UIImage(named:“image”), for: .normal, barMetrics: .default)
-
-
self.navigationItem.leftBarButtonItem = leftButton
效果如下图:
转载请注明:SuperIT » UIKit – UIBarButtonItem(导航按钮)