UIKit框架-高级控件:7.UIPickerView的自定义

在前面, 我们使用了UIPickerView试验了几次, 与其他UI控件结合在一起使用的也有, 今天我们就把UIPickerView剥的更深入, 让我们更加好的掌握UIPickerVIew, 下面让我们来看看



1.在.h文件里遵守UIPickerView的代理方法和数据源方法

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>

@end




2.在.m文件里声明全局变量

@interface ViewController ()
{
    UIPickerView *_pickerView;
    NSArray *_arrayOne;
    NSArray *_arrayTwo;
}
@end

PS:这两个数组分别是要用来存放UIPickerView的左右两边选择器的内容.



3.实例化UIPickerView

#pragma mark - 添加UIPikerView
- (void)myPikerView
{
    // 1.实例化UIPickerView
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 250, self.view.frame.size.width, 250)];
    [_pickerView setBackgroundColor:[UIColor grayColor]];
    
    // 2.设置UIPickerView的代理方法和数据源方法.
    [_pickerView setDelegate:self];
    [_pickerView setDataSource:self];
    
    // 3.设置是否显示内容
    [_pickerView setShowsSelectionIndicator:YES];
    
    // 4.把UIPickerView添加到self.view
    [self.view addSubview:_pickerView];
}


4.添加UIPickerView的数据源方法

// 返回UIPickerView有多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

// 返回UIPickerView有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return _arrayOne.count;
    } else {
        return _arrayTwo.count;
    }
}


5.添加UIPickerView的代理方法

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return _arrayOne[row];
    } else {
        return _arrayTwo[row];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSLog(@"第一列选中的行数是 %ld,第二列选中的行数是 %ld", [pickerView selectedRowInComponent:0], [pickerView selectedRowInComponent:1]);
    
    NSInteger leftCol = [pickerView selectedRowInComponent:0];
    NSInteger rightCol = [pickerView selectedRowInComponent:1];
    
    NSLog(@"%@ ~~~ %@", _arrayOne[leftCol], _arrayTwo[rightCol]);

}


6.定义数组的内容

- (void)myArray
{
    _arrayOne = @[@"辰东", @"唐家三少"];
    _arrayTwo = @[@"完美世界", @"天火大道", @"神墓"];
}



最终效果:






附件: UIPickerView的代理方法拓展

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 100;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UIView *views = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [views setBackgroundColor:[UIColor redColor]];
    return views;
}

效果:




好了, 这次我们就讲到这里, 下次我们继续~~

posted @ 2015-03-03 12:32  背着吉他去流浪  阅读(468)  评论(0编辑  收藏  举报