2016-06-12 53 views
0

我有一個函數應該通過在兩個圖像之間切換來「切換」一個條形按鈕項目。Swift - 動態添加的動作不會觸發

class Buttons { 
    func ToggleBarButton(button : UIBarButtonItem, name : String, location : BarButtonLocation, isEnabled : Bool, viewController : UIViewController) { 
     var iconName = name 
     if (!isEnabled) { 
      iconName += "EnabledIcon" 
     } else { 
      iconName += "DisabledIcon" 
     } 

     let newIcon = UIImage(named: iconName) 
     let newButton = UIBarButtonItem(image: newIcon, style: .Plain, target: self, action: button.action); 

     switch location { 
     case BarButtonLocation.Left: 
      viewController.navigationItem.leftBarButtonItem = newButton; 
      viewController.navigationItem.leftBarButtonItem?.tintColor = UIColor.blackColor(); 
     case BarButtonLocation.SecondLeft: 
      viewController.navigationItem.leftBarButtonItems?[1] = newButton 
      viewController.navigationItem.leftBarButtonItems?[1].tintColor = UIColor.blackColor() 
     default: 
      return; 
     } 
    } 
} 

我也有一個視圖控制器類,其中存在的欄按鈕項的動作。

class GradesViewController: UIViewController { 
    var isFilterEnabled = false 
    var isViewEnabled = false 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    @IBAction func filterButton_Pressed(sender: UIBarButtonItem) { 
     Buttons().ToggleBarButton(sender, name : "Filter", location: BarButtonLocation.Left, isEnabled: isFilterEnabled, viewController: self); 
     isFilterEnabled = !isFilterEnabled; 
    } 

    @IBAction func viewButton_Pressed(sender: UIBarButtonItem) { 
     Buttons().ToggleBarButton(sender, name : "View", location: BarButtonLocation.SecondLeft, isEnabled: isViewEnabled, viewController: self); 
     isViewEnabled = !isViewEnabled; 
    } 
} 

首先按下它成功地將圖像更改爲啓用的形式,但第二次按下它什麼都不做(按下事件甚至不會發生)。我檢查了,並且button.action被正確識別爲"filterButton_Pressed:"。有什麼問題,還是有更簡單的方法來做到這一點?提前感謝您的答覆。

+0

'Buttons()。ToggleBarButton(...)'在一個全新的'Buttons'實例上調用'ToggleBarButton'。這看起來不正確。 – dasblinkenlight

+0

@dasblinkenlight我剛剛意識到問題是我將視圖控制器中的代碼複製到按鈕類,並沒有將'target:self'更改爲'target:viewController'。現在它工作正常。但是現在我對這個新的按鈕實例感興趣......它應該如何正確寫入? –

+0

由於'Button'中的'ToggleBarButton'函數沒有使用實例變量,因此應該將其設置爲'static'(或'class',它是一樣的),並通過引用類名來調用它,而不是創建一個新實例。 – dasblinkenlight

回答

0

我剛剛意識到問題在於我將代碼從視圖控制器複製到按鈕類,並沒有將target: self更改爲target: viewController。但感謝所有的答案...

1

在每種情況下放置break語句並嘗試。 並且還刪除分號。

+0

當然,謝謝,但這不是問題。 (我想知道它爲什麼會起作用,它也應該切換另一個按鈕......) –

+0

@Geiszla中斷在switch語句中是可選的。半冒號也是可選的。 – Code

相關問題