UIPickerView的使用(三)


 

前兩篇文章 UIPickerView的使用(一)  、 UIPickerView的使用(二),學習了UIPickerView的單列選擇器和雙列選擇器的使用。

現在我們一起學習相互依賴的多列選擇器

 1、遵守協議

2、創建pickView

 

3、實現協議

//UIPickerViewDataSource中定義的方法,該方法的返回值決定該控件包含的列數
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
    return 2; // 返回2表明該控件只包含2列
}

//UIPickerViewDataSource中定義的方法,該方法的返回值決定該控件指定列包含多少個列表項
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    // 由於該控件只包含一列,因此無須理會列序號參數component
    // 該方法返回teams.count,表明teams包含多少個元素,該控件就包含多少行
    
    if (component == 0) {
        return _areas.count;
    }
    else
    
        return [[_teams objectForKey:_selectedAreas]count];
    
}


// UIPickerViewDelegate中定義的方法,該方法返回的NSString將作為UIPickerView
// 中指定列和列表項的標題文本
- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    // 由於該控件只包含一列,因此無須理會列序號參數component
    // 該方法根據row參數返回teams中的元素,row參數代表列表項的編號,
    // 因此該方法表示第幾個列表項,就使用teams中的第幾個元素
    
    if (component == 0) {
        return [_areas objectAtIndex:row];
    }
    return [[_teams objectForKey:_selectedAreas]objectAtIndex:row];
    
}

// 當用戶選中UIPickerViewDataSource中指定列和列表項時激發該方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if (component == 0) {
        _selectedAreas = [_areas objectAtIndex:row];
        [self.pickView reloadComponent:1];
        
    }
    
    NSArray *tmp = component == 0 ? _areas: [_teams objectForKey:_selectedAreas];
    
    NSString *tip = component == 0 ? @"區域":@"球隊";
    // 使用一個UIAlertView來顯示用戶選中的列表項
    UIAlertView* alert = [[UIAlertView alloc]
                          initWithTitle:@"提示"
                          message:[NSString stringWithFormat:@"你選中的%@是:%@"
                                   , tip ,[ tmp objectAtIndex:row]]
                          delegate:nil
                          cancelButtonTitle:@"確定"
                          otherButtonTitles:nil];
    [alert show];
}


// UIPickerViewDelegate中定義的方法,該方法返回的NSString將作為
// UIPickerView中指定列的寬度
-(CGFloat)pickerView:(UIPickerView *)pickerView
   widthForComponent:(NSInteger)component
{
    // 如果是第一列,寬度為90
    if(component == 0) {
        return 90;
    }
    return 210; // 如果是其他列(只有第二列),寬度為210
}

 

效果圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM