导航栏中的 UIBarButtonItem? ?

我一直在寻找这个解决方案,但没有一个。 例如,一种解决办法是

 self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: nil), animated: true)

此代码将添加一个带有“停止”图像的按钮。就像这样,还有其他的解决方案,比如“搜索”、“刷新”等等。但是 如果我想用编程方式添加一个按钮与我想要的图像?

217312 次浏览

只需使用 customView 设置 UIBarButtonItem

例如:

  var leftNavBarButton = UIBarButtonItem(customView:yourButton)
self.navigationItem.leftBarButtonItem = leftNavBarButton

或使用 setFunction:

  self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(customView: yourButton), animated: true);

自定义按钮图像,不设置按钮框架:

可以使用 init(image: UIImage?, style: UIBarButtonItemStyle, target: Any?, action: Selector?)使用指定的图像和其他属性初始化新项。

let button1 = UIBarButtonItem(image: UIImage(named: "imagename"), style: .plain, target: self, action: Selector("action")) // action:#selector(Class.MethodName) for swift 3
self.navigationItem.rightBarButtonItem  = button1

看看这个 苹果文件,参考文献


UIBarButtonItem 带有使用按钮框架的自定义按钮图像

对于 Swift 3.0

    let btn1 = UIButton(type: .custom)
btn1.setImage(UIImage(named: "imagename"), for: .normal)
btn1.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
btn1.addTarget(self, action: #selector(Class.Methodname), for: .touchUpInside)
let item1 = UIBarButtonItem(customView: btn1)


let btn2 = UIButton(type: .custom)
btn2.setImage(UIImage(named: "imagename"), for: .normal)
btn2.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
btn2.addTarget(self, action: #selector(Class.MethodName), for: .touchUpInside)
let item2 = UIBarButtonItem(customView: btn2)


self.navigationItem.setRightBarButtonItems([item1,item2], animated: true)

对于 Swift 2.0及以上

let btnName = UIButton()
btnName.setImage(UIImage(named: "imagename"), forState: .Normal)
btnName.frame = CGRectMake(0, 0, 30, 30)
btnName.addTarget(self, action: Selector("action"), forControlEvents: .TouchUpInside)


//.... Set Right/Left Bar Button item
let rightBarButton = UIBarButtonItem()
rightBarButton.customView = btnName
self.navigationItem.rightBarButtonItem = rightBarButton

或者简单地使用 Init (customView:)

 let rightBarButton = UIBarButtonItem(customView: btnName)
self.navigationItem.rightBarButtonItem = rightBarButton

用于 System UIBarButtonItem

let camera = UIBarButtonItem(barButtonSystemItem: .Camera, target: self, action: Selector("btnOpenCamera"))
self.navigationItem.rightBarButtonItem = camera

对于设置多于1个项目使用 rightBarButtonItems或左侧 leftBarButtonItems

let btn1 = UIButton()
btn1.setImage(UIImage(named: "img1"), forState: .Normal)
btn1.frame = CGRectMake(0, 0, 30, 30)
btn1.addTarget(self, action: Selector("action1:"), forControlEvents: .TouchUpInside)
let item1 = UIBarButtonItem()
item1.customView = btn1


let btn2 = UIButton()
btn2.setImage(UIImage(named: "img2"), forState: .Normal)
btn2.frame = CGRectMake(0, 0, 30, 30)
btn2.addTarget(self, action: Selector("action2:"), forControlEvents: .TouchUpInside)
let item2 = UIBarButtonItem()
item2.customView = btn2


self.navigationItem.rightBarButtonItems = [item1,item2]

使用 setLeftBarButtonItemsetRightBarButtonItem

let btn1 = UIButton()
btn1.setImage(UIImage(named: "img1"), forState: .Normal)
btn1.frame = CGRectMake(0, 0, 30, 30)
btn1.addTarget(self, action: Selector("action1:"), forControlEvents: .TouchUpInside)
self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(customView: btn1), animated: true);

对于 Swift > = 2.2,动作应该是 #selector(Class.MethodName)... 例如 btnName.addTarget(self, action: #selector(Class.MethodName), forControlEvents: .TouchUpInside)

我有同样的问题,我已经阅读了另一个主题的答案,然后我解决另一个类似的方式。我不知道哪个更有效。 类似的问题

//play button


@IBAction func startIt(sender: AnyObject) {
startThrough();
};


//play button


func startThrough() {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true);


let pauseButton = UIBarButtonItem(barButtonSystemItem: .Pause, target: self, action: "pauseIt");
self.toolBarIt.items?.removeLast();
self.toolBarIt.items?.append( pauseButton );
}


func pauseIt() {
timer.invalidate();


let play = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: "startThrough");
self.toolBarIt.items?.removeLast();
self.toolBarIt.items?.append( play );
}

我只是偶然发现了这个问题,下面是 Swift 3和 iOS 10的一个更新:

let testUIBarButtonItem = UIBarButtonItem(image: UIImage(named: "test.png"), style: .plain, target: self, action: nil)
self.navigationItem.rightBarButtonItem  = testUIBarButtonItem

这绝对比创建具有所有属性的 UIButton 然后将 customView 添加到 UIBarButtonItem 要快得多。

如果你想把图像的颜色从默认的蓝色改为白色,你可以随时改变色彩颜色:

test.tintColor = UIColor.white()

你显然应该更改应用程序的选择器等:)

在 Swift 3.0 + 中,UIBarButtonItem通过编程方式设置如下:

   override func viewDidLoad() {
super.viewDidLoad()
let testUIBarButtonItem = UIBarButtonItem(image: UIImage(named: "test.png"), style: .plain, target: self, action: #selector(self.clickButton))
self.navigationItem.rightBarButtonItem  = testUIBarButtonItem
}


@objc func clickButton(){
print("button click")
}

使用原始图像设置 LeftBarButton。

let menuButton = UIBarButtonItem(image: UIImage(named: "imagename").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(classname.functionname))
self.navigationItem.leftBarButtonItem  = menuButton
func viewDidLoad(){
let homeBtn: UIButton = UIButton(type: UIButtonType.custom)


homeBtn.setImage(UIImage(named: "Home.png"), for: [])


homeBtn.addTarget(self, action: #selector(homeAction), for: UIControlEvents.touchUpInside)


homeBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)


let homeButton = UIBarButtonItem(customView: homeBtn)




let backBtn: UIButton = UIButton(type: UIButtonType.custom)


backBtn.setImage(UIImage(named: "back.png"), for: [])


backBtn.addTarget(self, action: #selector(backAction), for: UIControlEvents.touchUpInside)


backBtn.frame = CGRect(x: -10, y: 0, width: 30, height: 30)


let backButton = UIBarButtonItem(customView: backBtn)
self.navigationItem.setLeftBarButtonItems([backButton,homeButton], animated: true)
}


}

使用 Swift 4Swift 4.2会容易得多

ViewDidLoad方法中,定义按钮并将其添加到导航栏。

override func viewDidLoad() {
super.viewDidLoad()


let logoutBarButtonItem = UIBarButtonItem(title: "Logout", style: .done, target: self, action: #selector(logoutUser))
self.navigationItem.rightBarButtonItem  = logoutBarButtonItem


}

然后您需要定义您在 action 参数中提到的函数,如下所示

@objc func logoutUser(){
print("clicked")
}

您需要添加 @objc前缀,因为它仍然在使用遗留内容(Objective C)。

这是苹果的疯狂之处。当你输入 selse.navationItem.right BarButtonItem.title 时,它会显示 nil,而在 GUI 上它会显示 Edit 或 Save。像我这样的新手需要很多时间来调试这种行为。

有一个要求,该项目将显示编辑在第一次加载,然后用户点击它,它会变成保存标题。为了存档这个,我做了如下。

//view did load will say Edit title

private func loadRightBarItem() {
let logoutBarButtonItem = UIBarButtonItem(title: "Edit", style: .done, target: self, action: #selector(handleEditBtn))
self.navigationItem.rightBarButtonItem  = logoutBarButtonItem
}

//点击“编辑”项将更改为“保存标题”

@objc private func handleEditBtn() {
print("clicked on Edit btn")
let logoutBarButtonItem = UIBarButtonItem(title: "Save", style: .done, target: self, action: #selector(handleSaveBtn))
self.navigationItem.rightBarButtonItem  = logoutBarButtonItem
blockEditTable(isBlock: false)
}

//点击保存项将显示编辑标题

@objc private func handleSaveBtn(){
print("clicked on Save btn")
let logoutBarButtonItem = UIBarButtonItem(title: "Edit", style: .done, target: self, action: #selector(handleEditBtn))
self.navigationItem.rightBarButtonItem  = logoutBarButtonItem


saveInvitation()
blockEditTable(isBlock: true)


}

IOS11

使用约束设置自定义按钮:

let buttonWidth = CGFloat(30)
let buttonHeight = CGFloat(30)


let button = UIButton(type: .custom)
button.setImage(UIImage(named: "img name"), for: .normal)
button.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside)
button.widthAnchor.constraint(equalToConstant: buttonWidth).isActive = true
button.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true


self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: button)

对于斯威夫特5 +

let searchBarButtonItem = UIBarButtonItem(image: UIImage(named: "searchIcon"), style: .plain, target: self, action: #selector(onSearchButtonClicked))
self.navigationItem.rightBarButtonItem  = searchBarButtonItem


@objc func onSearchButtonClicked(_ sender: Any){
print("SearchButtonClicked")
}

除了上述,您可以使用以下 ios14及以上

   if #available(iOS 14.0, *) {
let closeAction = UIAction(handler: { [weak self] _ in
//perform action here
})
let closeBarButtonItem = UIBarButtonItem(systemItem: .close, primaryAction: closeAction, menu: nil)
navigationItem.rightBarButtonItem  = closeBarButtonItem
}