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

UIPickerView的更多相关文章

  1. UIPickerView去掉背景上的黑线

    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger) ...

  2. [ios]新手笔记-。-UIPickerView 关于伪造循环效果和延时滚动效果

    查找了网上资料,循环效果绝大部分都是增加行数来制造循环的错觉,延时滚动就是利用NSTimer间隔出发滚动事件来制造滚动效果. 代码: #import <UIKit/UIKit.h>#imp ...

  3. UI控件(UIPickerView)

    @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; _item1 = [[NSArray alloc]i ...

  4. UIPickerView的使用(三)

    前两篇文章 UIPickerView的使用(一) . UIPickerView的使用(二),学习了UIPickerView的单列选择器和双列选择器的使用. 现在我们一起学习相互依赖的多列选择器 1.遵 ...

  5. UIPickerView的使用(二)

    上篇文章 UIPickerView的使用(一)学习了如何创建单列选择器,现在看一下如何创建多列选择器 多列选择器(以二列为例) 1.遵守协议和创建两个数据源 2.创建pickView 3.实现代理 / ...

  6. UIPickerView的使用(一)

    简介:UIPickerView是一个选择器控件,它比UIDatePicker更加通用,它可以生成单列的选择器,也可生成多列的选择器,而且开发者完全可以自定义选择项的外观,因此用法非常灵活.UIPick ...

  7. UIPickerView选择器的使用方法

    UIPickerView是选择列表内容的控件 使用方法与UITableView类似 都需要用array传入数据 用Delegate DataSource中的代理方法实现各种显示功能 @interfac ...

  8. iOS:选择器控件UIPickerView的详解和演示

    选择器控件UIPickerView: 功能:它能够创建一个类似于密码锁式的单列或多列的选择菜单,用户可以通过它设置的代理来选择需要菜单中的任意的数据.例如创建日历.字体表(类型.大小.颜色).图库等. ...

  9. UIPickerView滚轮选择器视图

    //必须实现两个协议 //数据源协议必须实现的两个方法 //选取器的输出借口singlePicker,并在故事版中选择该选取器将dataSource和delegate拖入视图控制器与之关联 //@pr ...

  10. iOs基础篇(二十二)—— UIPickerView、UIDatePicker控件的使用

    一.UIPickerView UIPickerView是一个选择器控件,可以生成单列的选择器,也可生成多列的选择器,而且开发者完全可以自定义选择项的外观,因此用法非常灵活. 1.常用属性 (1)num ...

随机推荐

  1. [转] Envelop

    xiaohaidepoli原文Envelop Envelope也称包络线,是一个矩形区域,是每个几何形体的最小外接矩形.每个Geometry都拥有一个Envelope,包括Envelope自身. 它定 ...

  2. 9、四大组件之四-Broadcast Receiver

    课程目标: 了解Android消息机制 掌握Broadcast发送消息的两种类型 掌握BroadcastReceiver接收消息的编程 重点难点: sendOrderedBroadcast()的理解 ...

  3. HDU 5965 Gym Class 贪心+toposort

    分析:就是给一些拓补关系,然后求最大分数,所以贪心,大的越靠前越好,小的越靠后越好 剩下的就是toposort,当然由于贪心,所以使用优先队列 #include <iostream> #i ...

  4. PPTP VPN不能打开百度

    问题: 在阿里云上设置PPTP VPN,电脑能正常连接,能打开京东 淘宝 QQ等没有问题,但是不能打开百度  糯米等网站.开始怀疑是代理设置问题,后面确认未设置独立规则. 1.从应用层看排除特殊规则设 ...

  5. [2015更新]用Word2007写CSDN博客

    搞了半天终于可以用word2007发布CSDN博客了,特分享出来,以方便其他用户. 所示的界面.     图1 office按钮 所示的管理账号,然后点击"新建"也可以进入图3所示 ...

  6. Idiomatic Python手记一: average in FP way

    方法一: import operator def average(*args): return reduce(operator.add, args) / len(args) if args else ...

  7. Matlab GUI界面

    做SVD的时候,看学姐的demo,用到了matlab的GUI,感兴趣就自己学了一下: 从简单的例子说起吧. 创建Matlab GUI界面通常有两种方式: 1,使用 .m 文件直接动态添加控件     ...

  8. jQuery.Autocomplete实现自动完成功能

    一.http://www.w3c.com.cn/jquery-plugin-autocomplete-参数及实例 二.jQuery plugin: Autocomplete 参数 minChars: ...

  9. 谈谈Nginx有哪些特点

    1.热部署        我个人觉得这个很不错.在master管理进程与worker工作进程的分离设计,使的Nginx具有热部署的功能,那么在7×24小时不间断服务的前提下,升级Nginx的可执行文件 ...

  10. Java 远程通讯技术及原理分析

    在分布式服务框架中,一个最基础的问题就是远程服务是怎么通讯的,在Java领域中有很多可实现远程通讯的技术,例如:RMI.MINA.ESB.Burlap.Hessian.SOAP.EJB和JMS等,这些 ...