iOS App中UIPickerView选择栏控件的使用实例解析

2020-01-15 14:28:19王旭

3、在ViewController.h中为Picker View控件创建Outlet映射,名称为myPickerView,然后为Select按钮创建Action映射,名称为buttonPressed,具体方法不说了,可以参照上一篇文章。
4、选中Picker View控件,打开Connections Inspector,找到delegate和datasource,从它们右边的圆圈拉线到File's Owner:

iOS,App,UIPickerView

5、单击ViewController.h,在其中添加代码:

复制代码
#import <UIKit/UIKit.h>

 

@interface ViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource>

@property (weak, nonatomic) IBOutlet UIPickerView *myPickerView;
@property (strong, nonatomic) NSArray *myPickerData;

- (IBAction)buttonPressed:(id)sender;

@end


 注意在@interface后面添加尖括号及其中内容,我们将ViewController作为Picker View的Delegate以及DataSource。

 

6、代码添加:

6.1 单击ViewController.m,在@implementation的下一行添加代码:

复制代码
@synthesize myPickerData;
6.2 找到buttonPressed方法,添加代码如下:
复制代码
- (IBAction)buttonPressed:(id)sender {
    NSInteger row = [myPickerView selectedRowInComponent:0]; 
    NSString *selected = [myPickerData objectAtIndex:row]; 
    NSString *msg = [[NSString alloc] initWithFormat: 
                       @"You selected %@!", selected]; 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello!" 
                                                    message:msg 
                                                   delegate:nil