使用 StoryBoard 在导航栏中使用 UIButton
Using a UIButton into Navigation Bar using StoryBoard
本质上,我在 StoryBoards 中创建了一个 UIButton,我想将它拖到导航栏中。这个 UIButton 在被触摸时有一个与之关联的动作,但是当我将这个 UIButton 拖到导航栏中时,所有触摸事件都停止工作。
执行此操作时,IBAction 项目是否需要额外的代码?
我想在导航栏中添加 UIButton 而不是 BarButtonItem 的主要原因之一是因为它允许我添加背景颜色并弯曲按钮的边缘。
我不认为你可以在情节提要中做到这一点。您必须使用 init(customView:)
初始化程序在代码中执行此操作。
let myCustomButtonWithBackgroundsAndStuff = UIButton(type: .custom)
...
// this is the equivalent of connecting the IBAction, in code form, in case you didn't know
myCustomButtonWithBackgroundsAndStuff.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: myCustomButton)
navigationItem.rightBarButtonItem = barButtonItem
// or append to rightBarButtonItems if you have other bar button items
...
@objc func buttonAction() {
...
}
本质上,我在 StoryBoards 中创建了一个 UIButton,我想将它拖到导航栏中。这个 UIButton 在被触摸时有一个与之关联的动作,但是当我将这个 UIButton 拖到导航栏中时,所有触摸事件都停止工作。
执行此操作时,IBAction 项目是否需要额外的代码?
我想在导航栏中添加 UIButton 而不是 BarButtonItem 的主要原因之一是因为它允许我添加背景颜色并弯曲按钮的边缘。
我不认为你可以在情节提要中做到这一点。您必须使用 init(customView:)
初始化程序在代码中执行此操作。
let myCustomButtonWithBackgroundsAndStuff = UIButton(type: .custom)
...
// this is the equivalent of connecting the IBAction, in code form, in case you didn't know
myCustomButtonWithBackgroundsAndStuff.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: myCustomButton)
navigationItem.rightBarButtonItem = barButtonItem
// or append to rightBarButtonItems if you have other bar button items
...
@objc func buttonAction() {
...
}