2016-07-09 28 views
0

我在我的工具栏中创建了一个自定义barButtonItem。我想在barButtonItem被点击时更改NSAttributedString的字符串。但是正如苹果文档所说,函数的性能是由customView而不是barButtonItem来支付的,我怎样才能根据事件访问并做一些细节变化?如何访问和更改由UIButton组成的自定义barButtonItem的NSAttributedString标题?

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) 

我是一个新swifter。 OC也可以由我读。 欢迎任何建议。谢谢。

回答

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) 
+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() 
    } 
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) 
} 
+0

谢谢。终于是我的解决方案。 –

+0

它是解决方案,请接受这个答案。 –