iphone的PickerView使用
1. File -> New Project -> View-based Application -> 输入工程名称 PickerView
2. PickerViewViewController.h
#import <UIKit/UIKit.h>
@interface PickerViewViewController : UIViewController<UIPickerViewDataSource, UIPickerViewDelegate>
{
UIPickerView *m_pPickerView;
NSArray *m_data;
}
@property (nonatomic, retain) IBOutlet UIPickerView *m_pPickerView;
@property (nonatomic, retain) NSArray *m_data;
@end
3. PickerViewViewController.m
#import "PickerViewViewController.h"
@implementation PickerViewViewController
@synthesize m_pPickerView, m_data;
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSArray *arr = [[NSArray alloc] initWithObjects:@"白菜", @"包心菜", @"**", @"韭菜", @"冬瓜", @"胡萝卜", @"竹笋", nil];
self.m_data = arr;
[arr release];
[super viewDidLoad];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
m_pPickerView = nil;
m_data = nil;
[super viewDidUnload];
}
- (void)dealloc {
[m_pPickerView release];
[m_data release];
[super dealloc];
}
#pragma mark -
#pragma mark Picker View Data Source Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [m_data count];
}
#pragma mark -
#pragma mark Picker View Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [m_data objectAtIndex:row];
}
@end
4. 双击 PickerViewViewController.xib, 按下shift + command + L, 拖一个PickerView 放到View上。
按下control 键同时从 File's Owner 拖动到 PickerView 控件上,连接输入口(IBOutlet).
按下 command + 2, 把 dataSource和delegate 拖动到File's Owner上。
5. 运行后的效果如下: