我是初学者iPhone开发者。
如何以编程方式设置UIBarButtonItem
的标题?
我的代码如下:
self.navigationItem.rightBarButtonItems =
UIBarButtonItem(
barButtonSystemItem: .Cancel, target: self,
action: "barButtonItemClicked:")
@IBAction func barButtonItemClicked(sender: UIBarButtonItem) {
//print something
}
答案 0 :(得分:26)
使用允许您指定标题的不同初始化程序:
UIBarButtonItem(title: "title", style: .Plain, target: self, action: "barButtonItemClicked:")
Swift 3.1更新
UIBarButtonItem(title: "title", style: .plain, target: self, action: #selector(barButtonItemClicked))
答案 1 :(得分:11)
Swift 2回答
您可以将以下内容添加到viewDidLoad
:
// Some text
self.barButtonItemClicked.title = "Right Button!"
OR
// A Unicode Gear Symbol
// See: http://graphemica.com/%E2%9A%99
self.barButtonItemClicked.title = "\u{2699}"
下面的ViewController.Swift
代码会设置您使用的名称barButtonItemClicked
。我使用了一个UIBarButtonItem来展示如何设置标题。但要使其适应功能是微不足道的。
import UIKit
class ViewController: UIViewController {
// Please make sure the line below is properly connected to your Storyboard!
@IBOutlet weak var barButtonItemClicked: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Set the text of the NavBarButtonItem Title
self.barButtonItemClicked.title = "Right Button!"
// Gear Icon
// self.barButtonItemClicked.title = "\u{2699}"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 2 :(得分:3)
就我而言,我想在编辑|完成之间切换。
但是,我无法使用leftBarButtonItem,因为我已经有了另一个UIBarButtonItem
。
我所做的是以下内容:
1-创建@IBOutlet weak var edit: UIBarButtonItem!
2-然后是一个变量来保持状态:var isEditingMode = false
3-现在在viewDidLoad
:
override func viewDidLoad() {
…
self.edit.action = #selector(self.toogleEditor(_:))
self.edit.title = "Edit"
self.setEditing(isEditingMode, animated: true)
…
}
我将edit.action选择器初始化为自定义函数toogleEditor
。我希望能够在行动发生时更改标题。
4-创建IBAction:
@IBAction func toogleEditor(sender: AnyObject) {
if isEditingMode
{
isEditingMode = false
self.edit.title = "Edit"
}
else
{
isEditingMode = true
self.edit.title = "Done"
}
self.setEditing(isEditingMode, animated: true)
}
每次用户点击UIBarItemButton
时都会触发此功能。
唯一要做的就是使用setEditing(…)
来更改UITableViewController
的行为。
答案 3 :(得分:1)
快捷键4:
@IBOutlet var saveButton: UIBarButtonItem!
saveButton.title = "Saved"
答案 4 :(得分:0)
来自文档
init(title title: String?,
style style: UIBarButtonItemStyle,
target target: AnyObject?,
action action: Selector)
答案 5 :(得分:0)