UIPickerView

1.UIPickView什么时候用?

通常在注册模块,当用户需要选择一些东西的时候,比如说城市,往往
弹出一个PickerView给他们选择。

UIPickView常见用法,演示实例程序

1> 独立的,没有任何关系 => 菜单系统。
2> 相关联的,下一列和第一列有联系=> 省会城市选择
3> 图文并帽, => 国旗选择

4.UIDatePicker什么时候用?
当用户选择日期的时候,一般弹出一个UIDatePicker给用户选择

 //
// ViewController.m
// 01-点餐系统
//
// Created by xiaomage on 15/6/9.
// Copyright (c) 2015年 xiaomage. All rights reserved.
// #import "ViewController.h" @interface ViewController ()<UIPickerViewDelegate,UIPickerViewDataSource> @property (weak, nonatomic) IBOutlet UIPickerView *pickerView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//设置代理方法方式如下,还有拖线,
self.pickerView.delegate = self; } // 返回pickerView有多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return ;
} // 返回第component列有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return ;
} #pragma mark - 代理
// 返回第component列的每一行的行高
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return 80.0;
} // 返回第component列第row行的标题
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return @"a";
} // NSAttributedString富文本属性: 可以描述文字大小和颜色
//- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component NS_AVAILABLE_IOS(6_0); // attributed title is favored if both methods are implemented // 总结:如果同时实现返回字符串和view的方法,返回UIView的优先级比较高
// 返回第component列第row行的View
//- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
//{
// UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
//
// v.backgroundColor = [UIColor redColor];
//
// return v;
//} // 选中第component第row的时候调用
// __func__: 返回当前方法在哪个类里面调用
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSLog(@"%s---%ld-%ld",__func__,component,row);
} @end
 //
// ViewController.m
// 01-点餐系统
//
// Created by xiaomage on 15/6/9.
// Copyright (c) 2015年 xiaomage. All rights reserved.
// #import "ViewController.h" // 分屏:cmd + option + return // 退出分屏:cmd + return @interface ViewController ()<UIPickerViewDelegate,UIPickerViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *frultLabel;
@property (weak, nonatomic) IBOutlet UILabel *mainLabel;
@property (weak, nonatomic) IBOutlet UILabel *drinkLabel; @property (weak, nonatomic) IBOutlet UIPickerView *pickerView; @property (nonatomic, strong) NSArray *foods; @end @implementation ViewController // 点击随机的时候调用
- (IBAction)random:(UIButton *)sender { // pickerView每一列随机选中一行 // 随机选中的文字展示到label // cmd + option + [ 代码上跳
// cmd + [ 代码左移
for (int i = ; i < ; i++) { // 假设让第0列随机选中一行
// 取出第0列的行数
NSInteger count = [self.foods[i] count]; int random = arc4random_uniform((u_int32_t)count);
// 不会触发代理的选中方法
[_pickerView selectRow:random inComponent:i animated:YES]; // 主动给label赋值
[self pickerView:nil didSelectRow:random inComponent:i];
} } - (NSArray *)foods
{
if (_foods == nil) { // 加载Pilst文件
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"foods.plist" ofType:nil]; // 大数组:pickerView有多少列
_foods = [NSArray arrayWithContentsOfFile:filePath]; } return _foods;
} - (void)viewDidLoad { [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. self.pickerView.delegate = self; // 初始化label标题 for (int i = ; i < ; i++) { [self pickerView:nil didSelectRow: inComponent:i]; } }
// 返回pickerView有多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return self.foods.count;
} // 返回第component列有多少行
- (NSInteger)r :(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [self.foods[component] count];
} // 返回第component列第row行的标题
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return self.foods[component][row];
} - (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return ;
} // 给label赋值
// 选中第component列第row行的时候调用
// 注意:这个方法必须用户主动拖动pickerView,才会调用
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{ switch (component) {
case :
// 设置水果
_frultLabel.text = self.foods[component][row];
break;
case :
// 设置主食
_mainLabel.text = self.foods[component][row];
break;
case :
// 设置饮料
_drinkLabel.text = self.foods[component][row];
break;
} } @end

pickerView返回一个view

 //
// ViewController.m
// 03-国旗选择
//
// Created by xiaomage on 15/6/9.
// Copyright (c) 2015年 xiaomage. All rights reserved.
// #import "ViewController.h" #import "XMGSubFlag.h" #import "XMGFlagView.h" @interface ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView; @property (nonatomic, strong) NSMutableArray *flags; @end @implementation ViewController //读取plist中的数据封装为模型
- (NSMutableArray *)flags
{
if (_flags == nil) { // 装flag模型
_flags = [NSMutableArray array]; // 加载plist
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"flags.plist" ofType:nil]; NSArray *arr = [NSArray arrayWithContentsOfFile:filePath]; for (NSDictionary *dict in arr) {
// 字典转模型
XMGFlag *flag = [XMGFlag flageWithDict:dict]; [_flags addObject:flag]; }
}
return _flags;
} - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. _pickerView.dataSource = self; _pickerView.delegate = self; } //数据源方法,返回列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return ;
}
//读取模型数组返回列有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{ return self.flags.count;
}
//代理方法 返回一个view
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
//xib获取view,传入模型
XMGFlagView *flagView = [[NSBundle mainBundle] loadNibNamed:@"XMGFlagView" owner:nil options:nil][]; // 取出对应的模型
XMGFlag *flag = self.flags[row];
flagView.flag = flag; return flagView;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return ;
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end
 //
// XMGFlag.h
// 03-国旗选择
//
// Created by xiaomage on 15/6/9.
// Copyright (c) 2015年 xiaomage. All rights reserved.
// #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface XMGFlag : NSObject @property (nonatomic, strong) NSString *name; @property (nonatomic, strong) UIImage *icon; // 写程序一定要有扩展性 // instancetype: 自动识别当前是哪个类在调用,就会变成对应类的对象 // 为什么不用id,id 不能使用点语法
// id 可以调用任何对象的方法,坏处:不利于编译器=检查错误
+ (instancetype)flageWithDict:(NSDictionary *)dict; @end //
// XMGFlag.m
// 03-国旗选择
//
// Created by xiaomage on 15/6/9.
// Copyright (c) 2015年 xiaomage. All rights reserved.
// #import "XMGFlag.h" #import <objc/message.h> @implementation XMGFlag + (instancetype)flageWithDict:(NSDictionary *)dict
{
XMGFlag *flag = [[self alloc] init]; // 利用KVC字典转模型
[flag setValuesForKeysWithDictionary:dict]; // [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
//
//
// NSString *funcName = [NSString stringWithFormat:@"set%@",key.capitalizedString];
//
// if ([flag respondsToSelector:@selector(funcName)]) {
//
// [flag setValue:obj forKeyPath:key];
//
// }
// }]; return flag;
} - (void)setIcon:(NSString *)icon
{
// NSLog(@"%s",__func__);
_icon = [UIImage imageNamed:icon];
} // 遍历字典里面所有的key // key:name
// 就去模型中查找有没有setName:,直接调用这个对象setName:赋值
// 假如没有找到setName:。就会去模型中查找有没有_name属性,_name = value
// 假如没有找到_name,还会去模型中查找name属性
// 最终没有找到,就会直接报错。 @end

模型

 //
// XMGFlagView.h
// 03-国旗选择
//
// Created by xiaomage on 15/6/9.
// Copyright (c) 2015年 xiaomage. All rights reserved.
// #import <UIKit/UIKit.h>
@class XMGFlag;
@interface XMGFlagView : UIView @property (nonatomic, strong) XMGFlag *flag; @end //
// XMGFlagView.m
// 03-国旗选择
//
// Created by xiaomage on 15/6/9.
// Copyright (c) 2015年 xiaomage. All rights reserved.
//
#import "XMGFlag.h"
#import "XMGFlagView.h" @interface XMGFlagView ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *label; @end @implementation XMGFlagView - (void)setFlag:(XMGFlag *)flag
{
_flag = flag; // 给子控件赋值
_label.text = flag.name;
_imageView.image = flag.icon;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/ @end

view

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="8191" systemVersion="15A284" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="8154"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="YWJ-6W-ap9" customClass="XMGFlagView">
<rect key="frame" x="0.0" y="0.0" width="375" height="60"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="bla-Fq-tBg">
<rect key="frame" x="0.0" y="0.0" width="90" height="60"/>
<animations/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
<nil key="highlightedColor"/>
</label>
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="LkB-3T-KX7">
<rect key="frame" x="278" y="0.0" width="102" height="65"/>
<animations/>
</imageView>
</subviews>
<animations/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<nil key="simulatedStatusBarMetrics"/>
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
<connections>
<outlet property="imageView" destination="LkB-3T-KX7" id="NPy-qW-igD"/>
<outlet property="label" destination="bla-Fq-tBg" id="FNP-89-PLs"/>
</connections>
<point key="canvasLocation" x="298.5" y="287"/>
</view>
</objects>
</document>

xib

生日键盘

 //
// ViewController.m
// 04-键盘处理
//
// Created by xiaomage on 15/6/9.
// Copyright (c) 2015年 xiaomage. All rights reserved.
// #import "ViewController.h" @interface ViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *birthdayField; @property (nonatomic, weak) UIDatePicker *datePicker; @end @implementation ViewController #pragma mark - UITextFieldDelegate
// 是否允许开始编辑
//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
//{
// return NO;
//} // 是否允许结束编辑
//- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
//{
// return NO;
//} // 是否允许用户输入文字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
return NO;
} // 文本框开始编辑的时候调用
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
// 给生日文本框赋值
[self dateChange:_datePicker];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_birthdayField.delegate = self; // 自定义生日键盘
[self setUpBirthdayKeyboard];
} // 自定义生日键盘
- (void)setUpBirthdayKeyboard
{
// 创建UIDatePicker
// 注意:UIDatePicker有默认的尺寸,可以不用设置frame
UIDatePicker *picker = [[UIDatePicker alloc] init]; _datePicker = picker; // 设置地区 zh:中国
picker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"]; // 设置日期的模式
picker.datePickerMode = UIDatePickerModeDate; // 监听UIDatePicker的滚动
[picker addTarget:self action:@selector(dateChange:) forControlEvents:UIControlEventValueChanged]; _birthdayField.inputView = picker;
} // 当UIDatePicker滚动的时候调用
// 给生日文本框赋值
- (void)dateChange:(UIDatePicker *)datePicker
{
NSLog(@"%@",datePicker.date);
// 日期转换字符串 NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; fmt.dateFormat = @"yyyy-MM-dd"; NSString *dateStr = [fmt stringFromDate:datePicker.date]; _birthdayField.text = dateStr;
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end
上一篇:GO语言练习:struct基础练习


下一篇:蜗牛爱课- CGAffineTransformMakeRotation 实现一张图片的自动旋转