0%

iOS开发 UIPickerView的使用(1)

先看效果图: 请无视下面的tab Bar,下面的代码跟它无关。 第一步,在xib文件添加一个UIPickerView,和一个Round Rect Button,如图上所示。 第二步,在编辑UI的窗口中,选中UIPickerView,打开Connection inspector,按住Control键,分别拖动dataSource和delegate右边的小圈到左边Placeholders下的File’s Owner(新版的XCode就是View Controller),建立连接。 第三步,按住control键,拖动UIPickerView到ViewController.h文件中,创建outlet,同样的方法为按钮创建action viewController.h代码如下:

#import 

#define kFillingComponent 0
#define kBreadComponent 1
@interface DoubleComponentPickerViewController : UIViewController

//必须添加这两个协议
@property (strong, nonatomic) IBOutlet UIPickerView *doublePickers;
@property (strong,nonatomic) NSArray *fillingTypes;
@property (strong,nonatomic) NSArray *breadTypes;
//两个array用于存储两个选择器的选项
- (IBAction)buttonPressed;
@end

viewController.m内容如下:

#import "DoubleComponentPickerViewController.h"

@implementation DoubleComponentPickerViewController
@synthesize doublePickers;
@synthesize fillingTypes=_fillingTypes,breadTypes=_breadTypes;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *fillingArray=[[NSArray alloc] initWithObjects:@"aaa",@"bbb",@"ccc",@"ddd", nil];
    _fillingTypes=fillingArray;
    NSArray *breadArray=[[NSArray alloc] initWithObjects:@"111",@"222",@"333",@"444", nil];
    _breadTypes=breadArray;
//启动时载入数组
}

- (void)viewDidUnload
{
    [self setDoublePickers:nil];
    [super viewDidUnload];
    _fillingTypes=nil;
    _breadTypes=nil;
    //关闭时清空
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)buttonPressed {
    NSInteger * fillingRow=[doublePickers selectedRowInComponent:kFillingComponent];
    NSInteger * breadRow=[doublePickers selectedRowInComponent:kBreadComponent];
    NSString *string=[NSString stringWithFormat:@"%@ %@",[_fillingTypes objectAtIndex:fillingRow],[_breadTypes objectAtIndex:breadRow]];
    NSLog(@"%@",string);
    //读取选择的结果
    
}
//下面的方法都是协议中定义的
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
    //定义选择器数量
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(component==kBreadComponent)
        return [_breadTypes count];
    return [_fillingTypes count];
    //选项数量
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    if(component==kBreadComponent)
        
        return [_breadTypes objectAtIndex:row];
    
    return [_fillingTypes objectAtIndex:row];
    //选项的文字
    
}
@end

如果只要一个选择器,更简章,稍做修改就可实现。