如何访问和更改由UIButton组成的自定义barButtonItem的NSAttributedString标题?

时间:2016-07-09 02:25:00

标签: ios swift uibutton uibarbuttonitem

我在工具栏中创建了一个自定义barButtonItem。我想在点击barButtonItem时更改NSAttributedString的字符串。但正如苹果文档所说,该功能的性能由customView而不是barButtonItem负责,我如何根据事件访问并对其细节进行一些更改?

    let button1 = UIButton(type: .System)
    button1.sizeToFit()
    let attributes1 = [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(13)]
    let attributedString1 = NSAttributedString(string: "Hello", attributes: attributes1)
    button1.setAttributedTitle(attributedString1, forState: .Normal)
    button1.addTarget(self, action: #selector(ActionViewController.switchAccounts), forControlEvents: .TouchUpInside)
    let account = UIBarButtonItem(customView: button1)

    setToolbarItems([account], animated: true)

我是一个新的快捷方式。我也可以阅读OC。 欢迎任何建议。感谢。

3 个答案:

答案 0 :(得分:0)

有没有人发现stackoverflow可以用作一只小黄鸭?洛尔

for item in toolbarItems! where item.tag == 1000 {
        let attributes1 = [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(13)]
        let attributedString1 = NSAttributedString(string: "world!", attributes: attributes1)

        let button = item.customView as! UIButton
        button.setAttributedTitle(attributedString1, forState: .Normal)
        button.sizeToFit()
    }

答案 1 :(得分:0)

您可以像这样使用自定义按钮操作方法

func switchAccounts(sender : UIButton)  {
    let attributes1 = [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(13)]
    let attributedString1 = NSAttributedString(string: "world!", attributes: attributes1)

    sender.setAttributedTitle(attributedString1, forState: .Normal)
    sender.sizeToFit()
}

button1.addTarget(self, action: #selector(ActionViewController.switchAccounts(_:))

而不是

button1.addTarget(self, action: #selector(ActionViewController.switchAccounts)

答案 2 :(得分:0)

更改目标代码,如下所示。

button1.addTarget(self, action: #selector(ActionViewController.switchAccounts(_:)), forControlEvents: .TouchUpInside)

如下所示 switchAccounts()

func switchAccounts(sender:UIButton){
    sender.selected = !sender.selected
    let attributes1 = [NSForegroundColorAttributeName: UIColor.redColor(), NSFontAttributeName: UIFont.systemFontOfSize(13)]
    let attributedString1 = NSAttributedString(string: "Hello click", attributes: attributes1)
    sender.setAttributedTitle(attributedString1, forState: .Selected)
}