UIPickerView 选择器

作者: 阿年同学 | 来源:发表于2016-07-22 20:28 被阅读251次

    UIPickerView继承自UIView,所以不能像UIControl样绑定事件处理方法,所以UIPickerView的事件处理由其委托对象完成。

    @interface ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
    
    _myPicker = [[UIPickerView alloc] init];
    
    //设置高亮显示
    _myPicker.showsSelectionIndicator = YES;
    
    //数据源
    _myPicker.dataSource = self;
    //代理
    _myPicker.delegate = self;
    
    //放在正中间
    _myPicker.center = self.view.center;
    
    //显示的时候是第几个,索引是从0开始的,显示第5个
    [_myPicker selectRow:4 inComponent:0 animated:YES];
    //第二列,也是第5个
    [_myPicker selectRow:4 inComponent:1 animated:YES];
    
    [self.view addSubview:_myPicker];
    

    numberOfComponents:获取指定列中的列表项的数量,只读属性
    showsSelectionIndicato:是否显示UIPickerView中的选中标记(以高亮背景作为选中标记)
    -numberOfRowsInComponent: 获取列的数量
    -rowSizeForComponent: 获取指定列中列表项的大小。返回CGSize对象
    -selectRow:inComponent:animated:设置指定列的特定列表项。是否使用动画

    UIPickerViewDataSource :
    控制包含多少列,每一列又包含多少列表项(也是是行)

    //设置数据源方法,返回2表示有两列
    
    // returns the number of 'columns' to display.
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView  *)pickerView
    {
        return 2;
    }
    
    //设置每一列,有多少行
    // returns the # of rows in each component..
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    {
        //先定义一个变量
        NSInteger result;
        //判断
        if (component == 0) {
            //是第一列的时候,给5行
            result = 5;
        } else if (component == 1){
            //第二列,给10行
            result = 10;
        }
        //返回数值
        return result;
        
    }
    
    
    
    
    //设置协议方法
    
    //每一列宽度
    // returns width of column and height of row for each component.
    - (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
    {
        return 150;
    }
    
    //每一行显示的数据
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
        //返回的是NSString类型的数据
        //返回每一行,因为索引是从0开始,+1
        NSString *result = [NSString stringWithFormat:@"我是第%ld行",(long)row + 1];
        return result;
    }
    
    UIpickerView.gif

    PS:话说这个大概可以和日期相结合吧,回头试一下

    相关文章

      网友评论

        本文标题:UIPickerView 选择器

        本文链接:https://www.haomeiwen.com/subject/uqiijttx.html