2016-07-09 29 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

它是解決方案,請接受這個答案。 –