• (三十)PickerView文字和随机数的使用


    PickerView用于展示供选择的内容(例如日期选取、点菜等)。

    有三种情况:

    1.每一列都是独立的选取

    2.右边的列受到左边列的影响

    3.包含图片


    PickerView和TableView类似,通过数据源来显示数据,与TableView同样地,让控制器称为其数据源。

    但是PickerView的数据源仅仅提供行数和列数,在代理方法内才能设置内容。

    通过两个数据源方法设置行和列数,通过一个代理方法来设定内容,注意component表示第几列:

    这里的foods成员是一个复合数组,即NSArray内又有多个NSArray,每个内层的NSArray中放着一个类型的食物,不同内层NSArray之间代表不同类型的食物。

    要得到这样的复合数组,可以直接建立,例如:

    @[@[...],@[...],@[...]];
    或者通过plist读取,plist读取的方法在(二十七)QQ好友列表的实现的开头有提到。

    #pragma mark - PickerView数据源方法
    
    // returns the number of 'columns' to display.
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
        return self.foods.count;
    }
    
    // returns the # of rows in each component..
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
        NSArray *foodArray = self.foods[component]; // component是列
        return foodArray.count;
    }
    
    #pragma mark - PickerView代理方法
    
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
        return self.foods[component][row];
    }
    要监听选择,只需要再实现一个代理方法:

    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
        NSString *name = self.foods[component][row];
        switch (component) {
            case 0:
                self.fruitLabel.text = name;
                break;
            case 1:
                self.mainLabel.text = name;
                break;
            case 2:
                self.drinkLabel.text = name;
                break;
            default:
                break;
        }
    }

    一个细节:没有点选时的显示数据初始化:

    间接利用上面的选择方法来初始化数据:每列都选中第0行,由于用不到pickerView本身,因此传入nil也无妨。

    for (int i = 0; i < self.foods.count; i++) {
            [self pickerView:nil didSelectRow:0 inComponent:i];
        }

    Tip:键盘上方常常用导航工具条,用于切换上一项、下一项等内容。

    直接获取当前的选取项:selectRowInComponent: 传入列号可以得到选中的是第几行。


    随机数:

    arc4random()可以产生0或者正整数,要产生0 ~ (x-1)的随机数,应该使用 arc4random( ) % x。


    关于选择层次的设计(选择左边右边变化),是由代码实现的(更换列的数据)。

    需要用到reloadAllComponents或者reloadComponent:方法。


  • 相关阅读:
    解决在Apple Silicon (M1)安装php MongoDB扩展失败
    dyld: Library not loaded: /usr/local/opt/libpng/lib/libpng16.16.dylib
    docker自建bitwarden_rs服务器更新支持send功能
    centos安装puppeteer遇到的报错及解决方案
    Centos宝塔安装NextCloud
    苹果设备型号代码(更新至iPhone12)
    electron内使用vue-slider-component组件报“$attrs is readonly”错误
    ZSH隐藏命令行前面的用户名和主机名
    Android9.0配置charles的https抓包
    记一次discuz修改首页图片路径问题
  • 原文地址:https://www.cnblogs.com/aiwz/p/6154222.html
Copyright © 2020-2023  润新知