IOS 开发之PickerView文字和随机数的使用

2025-05-29 0 96

IOS 开发之PickerView文字和随机数的使用

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

有三种情况:

1.每一列都是独立的选取
2.右边的列受到左边列的影响
3.包含图片

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

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

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

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

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

?

1
@[@[...],@[...],@[...]];

或者通过plist读取

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
#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];

}

要监听选择,只需要再实现一个代理方法:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16
- (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也无妨。

?

1

2

3
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:方法。

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 IOS 开发之PickerView文字和随机数的使用 https://www.kuaiidc.com/90907.html

相关文章

发表评论
暂无评论