标签:
//
// ViewController.m
// 哦喔喔
//
// Created by 殷婷婷 on 15-7-10.
// Copyright (c) 2015年 lanou. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()<UIPickerViewDelegate,UIPickerViewDataSource>
@property(nonatomic,strong)NSArray *foods;
@end
@implementation ViewController
- (NSArray *)foods{
if (_foods == nil) {
NSString *path = [[NSBundle mainBundle]pathForResource:@"foods.plist" ofType:nil];
_foods = [NSArray arrayWithContentsOfFile:path];
}
return _foods;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//默认选中每行的第0个
for (int i = 0; i < self.foods.count; i++) {
[self pickerView:self.myPickerView didSelectRow:0 inComponent:i];
}
}
//datasource代理方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return self.foods.count;
}
//datasource代理方法,就这两个代理方法
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
NSArray *juti = self.foods[component];
return juti.count;
}
//delegate代理方法
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
NSArray *juti = self.foods[component];
return juti[row];
}
//因为原row的字体过大,很难看。没有找到可以设置字体的方法。所以自定义了一个view.注意,将title赋值给label.text
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
//系统控件不用设置frame,自定义控件要设置
//注意这里也有重用机制
UILabel *label = (UILabel *)view;
if (label == nil) {
label = [[UILabel alloc]init];
label.font = [UIFont systemFontOfSize:13.0];
label.backgroundColor = [UIColor redColor];
label.text = [self pickerView:pickerView titleForRow:row forComponent:component];
}
return label;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
NSArray *juti = self.foods[component];
NSString *name = juti[row];
switch (component) {
case 0:
self.fruitLabel.text = name;
break;
case 1:
self.caiLbel.text = name;
break;
case 2:
self.drinkLabel.text = name;
break;
default:
break;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)randomBtnClick:(id)sender {
for (int i = 0; i < self.foods.count; i++) {
NSArray *juti = self.foods[i];
//注意这里的强转
NSInteger row = arc4random_uniform((int)juti.count);
NSInteger old = [self.myPickerView selectedRowInComponent:i];
while (row == old) {
row = arc4random_uniform((int)juti.count);
}
//更改pickerView选中的项
[self.myPickerView selectRow:row inComponent:i animated:YES];
//更改label显示的文字
[self pickerView:self.myPickerView didSelectRow:row inComponent:i];
}
}
@end
标签:
原文地址:http://www.cnblogs.com/yintingting/p/4638739.html