2015-06-18 25 views
0

背景: 我正在開發一個供其他應用程序開發人員使用的插件。如果他們有一個UIPickerView,我希望能夠在用戶與PickerView交互時做出反應。如何檢測與UIPickerView的交互,當我不擁有代表

這意味着我無法設置UIPickerViewDelegate。對於UITextFields,我可以使用addTarget,因爲它從UIControl擴展而來。那麼當我不知道它的上下文時,我將如何去聽UIPickerView中的更改?我更喜歡在Swift中做到這一點。

+0

您可以使用類別,使onValueChanged發送通知。 任何想遵守該UIPickerView的人都需要遵守該通知。 – Erakk

+0

你能否詳細說明一下?我無法在UIPickerView中找到onValueChanged。鑑於它存在,我如何檢測它的變化?而且我不能重寫didSelectItem方法,因爲這會混淆它的實現。 –

回答

0

也許您可以將UIPickerViewDelegate設置爲您的插件,並通過自定義YourPluginDelegate委託(某些)功能。通過這種方式,你和你的用戶將能夠檢測到事件。而且這是離開你實現的一個抽象層。

代碼示例:

你的插件:

 
func pickerView(pickerView: UIPickerView, 
     titleForRow row: Int, 
     forComponent component: Int) -> String!{ 

     //do your things here 

     let response = self.pluginDelegate.plugin(self, titleForRow: row, forComponent: component) 
     return response 
} 

YourPluginDelegate:

 
protocol YourPlugInDelegate{ 
    func plugin(plugin:PlugIn, titleForRow row: Int, forComponent component:Int)->String! 
}