網頁

2013年2月21日 星期四

Datasource and Delegate 的分別 (3) 照著 datasource Protocol 辦事

[iphone app 開發] 完成datasource 的protocol.


ok, 知道了每個控制項(ex: picker view) 要實作自己的datasource and delegate 後,
那如果每個開發者都自己亂做,或是不照著apple 想要的作,那這個picker view 豈不是
相當難維護,且天下大亂嗎?

所以,apple 在document 中就寫明了,那些method 是 picker 的 datasource 必須實作的,怎麼實作,和回傳什麼值,delegate 也是,所以,換言之。





=>要讓picker view 動起來,得分別實作 datasource 和 delegate 中apple 規定必須做的method.


如上圖,它告訴你了datasource 和 delegate 的介紹,如果想知道

datasource 怎麼實作,點進去.....



這邊你就會看到,要實作datasource 的 協議 (Protocol ) 需要下面那些東西....

其中它提到,Providing counts for the picker view...

就是說,下面那兩個 method 是一定要做的,分別有意義的回傳值給
picker view.....


且,照我們前面說的,picker view 會跟datasource 索取它要怎麼show 的資訊
,所以你也能預料,下面這兩個必須要作的方法,其回傳值,應該就是要幫助picker view 去show 它的樣子....

分別的定義查詢doc 就能清楚知道....


- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView



Return Value
The number of components (or “columns”) that the picker view should display.

簡單講,要告訴picker view 有幾個垂直的行要表現。





- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component



Return Value
The number of rows for the component.

假設有兩行的資料要表現,分別告訴picker view 第一行有幾個data 要show, 也就是
分別告訴picker view 每個column 的 row 數。  不是真正的data 歐,只有數量。


ex:

//實作下面兩個datasource function 來自於apple doc 的要求
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
        return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{

    if (component==0) {
        
        return [activities_ count];
    }else{
    
        return [actions_ count];
    }
    
}



當然,你要先把 activites_ 和 actions_ 這兩個陣列在 - (void)viewDidLoad
裡面 init 好...

編譯之後....





你會發現,picker view 裡面還是白白的一片,什麼都沒有....

最後記得,要把datasource 的outlets 連結起來
view 才會動歐!





再次編譯後的結果....




這次,會出現一堆問號,不過呢,你可看到,picker view 有兩行,這是因為
我們在
  - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
        return 2;
}
hard code 回傳2.


而個別的數量(這邊就是問號的數量),就是當初你宣告activites_ 和 actions_ 這兩個陣列
的數量摟!














沒有留言:

張貼留言