您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

動手改造 UIPickerView:讓「一列」承載三列內容

編輯:iOS 開發基礎

UIPickerView 的核心其實不複雜:一個 UIPickerView 類別,加上 UIPickerViewDelegate 與 UIPickerViewDataSource 兩個協議,分別負責代理與資料來源。這些基礎這裡不再細談,本文只針對一個具體需求來解題。

一般情況下,UIPickerView 可以定義多列內容,例如年、月、日三欄,彼此互不干擾,各滾各的。但我們遇到的需求剛好相反:同樣是三欄,卻必須綁在一起同步滾動。這就得換個思路處理了。

UIPickerViewDelegate 裡聲明了這樣一個代理方法:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view

透過它,我們就能自定義每一列的視圖呈現方式。廢話不多說,直接看程式碼:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { PickerViewCell *pickerCell = (PickerViewCell *)view; if (!pickerCell) { NSInteger column = 3; pickerCell = [[PickerViewCell alloc] initWithFrame:(CGRect){CGPointZero, [UIScreen mainScreen].bounds.size.width, 45.0f} column:column]; } [pickerCell setLabelTexts:@[...]]; return pickerCell; }

我們自訂了一個 PickerViewCell,內部依傳入的 column 參數把寬度等分成 column 份,放進相同數量的 UILabel,再由 setLabelTexts 逐一填入文字。當然,各個 UILabel 的外觀樣式也在 PickerViewCell 裡一併定義。就這麼簡單。

但有個細節必須留意:畫面上看起來是三欄,系統實際上仍舊當成一列處理,所以下面這個方法要回傳 1:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 1; }

換句話說,三欄同步滾動的效果,是靠一個自訂視圖在單一 component 內「假裝」出來的。

參考

  1. UIPickerViewDelegate Protocol Reference

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved