zoukankan      html  css  js  c++  java
  • UIPickerView

    1.UIPickView什么时候用?

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

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

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

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

     1 //
     2 //  ViewController.m
     3 //  01-点餐系统
     4 //
     5 //  Created by xiaomage on 15/6/9.
     6 //  Copyright (c) 2015年 xiaomage. All rights reserved.
     7 //
     8 
     9 #import "ViewController.h"
    10 
    11 @interface ViewController ()<UIPickerViewDelegate,UIPickerViewDataSource>
    12 
    13 @property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
    14 
    15 @end
    16 
    17 @implementation ViewController
    18 
    19 - (void)viewDidLoad {
    20     
    21     [super viewDidLoad];
    22     // Do any additional setup after loading the view, typically from a nib.
    23   //设置代理方法方式如下,还有拖线,  
    24     self.pickerView.delegate = self;
    25     
    26 }
    27 
    28 
    29 // 返回pickerView有多少列
    30 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
    31 {
    32     return 3;
    33 }
    34 
    35 // 返回第component列有多少行
    36 - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    37 {
    38     return 2;
    39 }
    40 
    41 
    42 #pragma mark - 代理
    43 // 返回第component列的每一行的行高
    44 - (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
    45 {
    46     return 80.0;
    47 }
    48 
    49 // 返回第component列第row行的标题
    50 - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
    51 {
    52     return @"a";
    53 }
    54 
    55 // NSAttributedString富文本属性: 可以描述文字大小和颜色
    56 //- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component NS_AVAILABLE_IOS(6_0); // attributed title is favored if both methods are implemented
    57 
    58 
    59 // 总结:如果同时实现返回字符串和view的方法,返回UIView的优先级比较高
    60 // 返回第component列第row行的View
    61 //- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
    62 //{
    63 //    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    64 //    
    65 //    v.backgroundColor = [UIColor redColor];
    66 //    
    67 //    return v;
    68 //}
    69 
    70 // 选中第component第row的时候调用
    71 // __func__: 返回当前方法在哪个类里面调用
    72 - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    73 {
    74     NSLog(@"%s---%ld-%ld",__func__,component,row);
    75 }
    76 
    77 
    78 @end
    View Code
      1 //
      2 //  ViewController.m
      3 //  01-点餐系统
      4 //
      5 //  Created by xiaomage on 15/6/9.
      6 //  Copyright (c) 2015年 xiaomage. All rights reserved.
      7 //
      8 
      9 #import "ViewController.h"
     10 
     11 // 分屏:cmd + option + return
     12 
     13 // 退出分屏:cmd + return
     14 
     15 @interface ViewController ()<UIPickerViewDelegate,UIPickerViewDataSource>
     16 @property (weak, nonatomic) IBOutlet UILabel *frultLabel;
     17 @property (weak, nonatomic) IBOutlet UILabel *mainLabel;
     18 @property (weak, nonatomic) IBOutlet UILabel *drinkLabel;
     19 
     20 @property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
     21 
     22 
     23 @property (nonatomic, strong) NSArray *foods;
     24 
     25 @end
     26 
     27 @implementation ViewController
     28 
     29 // 点击随机的时候调用
     30 - (IBAction)random:(UIButton *)sender {
     31     
     32     // pickerView每一列随机选中一行
     33     
     34     // 随机选中的文字展示到label
     35     
     36     // cmd + option + [ 代码上跳
     37     // cmd + [ 代码左移
     38     for (int i = 0; i < 3; i++) {
     39         
     40         // 假设让第0列随机选中一行
     41         // 取出第0列的行数
     42         NSInteger count = [self.foods[i] count];
     43         
     44         int random = arc4random_uniform((u_int32_t)count);
     45         // 不会触发代理的选中方法
     46         [_pickerView selectRow:random inComponent:i animated:YES];
     47         
     48         // 主动给label赋值
     49         [self pickerView:nil didSelectRow:random inComponent:i];
     50     }
     51     
     52 }
     53 
     54 - (NSArray *)foods
     55 {
     56     if (_foods == nil) {
     57         
     58         // 加载Pilst文件
     59        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"foods.plist" ofType:nil];
     60         
     61         // 大数组:pickerView有多少列
     62         _foods = [NSArray arrayWithContentsOfFile:filePath];
     63         
     64     }
     65     
     66     return _foods;
     67 }
     68 
     69 - (void)viewDidLoad {
     70     
     71     [super viewDidLoad];
     72     // Do any additional setup after loading the view, typically from a nib.
     73     
     74     self.pickerView.delegate = self;
     75     
     76     // 初始化label标题
     77     
     78     for (int i = 0; i < 3; i++) {
     79         
     80         [self pickerView:nil didSelectRow:0 inComponent:i];
     81         
     82     }
     83     
     84 }
     85 // 返回pickerView有多少列
     86 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
     87 {
     88     return self.foods.count;
     89 }
     90 
     91 // 返回第component列有多少行
     92 - (NSInteger)r :(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
     93 {
     94     return [self.foods[component] count];
     95 }
     96 
     97 // 返回第component列第row行的标题
     98 - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
     99 {
    100     return self.foods[component][row];
    101 }
    102 
    103 
    104 - (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
    105 {
    106     return 45;
    107 }
    108 
    109 // 给label赋值
    110 // 选中第component列第row行的时候调用
    111 // 注意:这个方法必须用户主动拖动pickerView,才会调用
    112 - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    113 {
    114     
    115     switch (component) {
    116         case 0:
    117             // 设置水果
    118             _frultLabel.text = self.foods[component][row];
    119             break;
    120         case 1:
    121             // 设置主食
    122             _mainLabel.text = self.foods[component][row];
    123             break;
    124         case 2:
    125             // 设置饮料
    126             _drinkLabel.text = self.foods[component][row];
    127             break;
    128     }
    129     
    130     
    131 }
    132 
    133 
    134 @end
    View Code

    pickerView返回一个view

     1 //
     2 //  ViewController.m
     3 //  03-国旗选择
     4 //
     5 //  Created by xiaomage on 15/6/9.
     6 //  Copyright (c) 2015年 xiaomage. All rights reserved.
     7 //
     8 
     9 #import "ViewController.h"
    10 
    11 #import "XMGSubFlag.h"
    12 
    13 #import "XMGFlagView.h"
    14 
    15 @interface ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
    16 @property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
    17 
    18 @property (nonatomic, strong) NSMutableArray *flags;
    19 
    20 @end
    21 
    22 @implementation ViewController
    23 
    24 //读取plist中的数据封装为模型
    25 - (NSMutableArray *)flags
    26 {
    27     if (_flags == nil) {
    28         
    29         // 装flag模型
    30         _flags = [NSMutableArray array];
    31         
    32         // 加载plist
    33         NSString *filePath = [[NSBundle mainBundle] pathForResource:@"flags.plist" ofType:nil];
    34         
    35         NSArray *arr = [NSArray arrayWithContentsOfFile:filePath];
    36         
    37         for (NSDictionary *dict in arr) {
    38             // 字典转模型
    39             XMGFlag *flag = [XMGFlag flageWithDict:dict];
    40             
    41             [_flags addObject:flag];
    42             
    43         }
    44     }
    45     return _flags;
    46 }
    47 
    48 - (void)viewDidLoad {
    49     [super viewDidLoad];
    50     // Do any additional setup after loading the view, typically from a nib.
    51    
    52     
    53     _pickerView.dataSource = self;
    54     
    55     _pickerView.delegate = self;
    56     
    57 }
    58 
    59 //数据源方法,返回列数
    60 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
    61 {
    62     return 1;
    63 }
    64 //读取模型数组返回列有多少行
    65 - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    66 {
    67     
    68     return self.flags.count;
    69 }
    70 //代理方法 返回一个view 
    71 - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
    72 {
    73 //xib获取view,传入模型
    74     XMGFlagView *flagView = [[NSBundle mainBundle] loadNibNamed:@"XMGFlagView" owner:nil options:nil][0];
    75     
    76     // 取出对应的模型
    77     XMGFlag *flag = self.flags[row];
    78     flagView.flag = flag;
    79     
    80     return flagView;
    81 }
    82 - (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
    83 {
    84     return 60;
    85 }
    86 
    87 - (void)didReceiveMemoryWarning {
    88     [super didReceiveMemoryWarning];
    89     // Dispose of any resources that can be recreated.
    90 }
    91 
    92 @end
    View Code
     1 //
     2 //  XMGFlag.h
     3 //  03-国旗选择
     4 //
     5 //  Created by xiaomage on 15/6/9.
     6 //  Copyright (c) 2015年 xiaomage. All rights reserved.
     7 //
     8 
     9 #import <Foundation/Foundation.h>
    10 
    11 #import <UIKit/UIKit.h>
    12 
    13 @interface XMGFlag : NSObject
    14 
    15 @property (nonatomic, strong) NSString *name;
    16 
    17 @property (nonatomic, strong) UIImage *icon;
    18 
    19 // 写程序一定要有扩展性
    20 
    21 // instancetype: 自动识别当前是哪个类在调用,就会变成对应类的对象
    22 
    23 // 为什么不用id,id 不能使用点语法
    24 // id 可以调用任何对象的方法,坏处:不利于编译器=检查错误
    25 + (instancetype)flageWithDict:(NSDictionary *)dict;
    26 
    27 @end
    28 
    29 
    30 //
    31 //  XMGFlag.m
    32 //  03-国旗选择
    33 //
    34 //  Created by xiaomage on 15/6/9.
    35 //  Copyright (c) 2015年 xiaomage. All rights reserved.
    36 //
    37 
    38 #import "XMGFlag.h"
    39 
    40 #import <objc/message.h>
    41 
    42 @implementation XMGFlag
    43 
    44 + (instancetype)flageWithDict:(NSDictionary *)dict
    45 {
    46     XMGFlag *flag = [[self alloc] init];
    47     
    48     // 利用KVC字典转模型
    49     [flag setValuesForKeysWithDictionary:dict];
    50     
    51     
    52 //    [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
    53 //        
    54 //        
    55 //        NSString *funcName = [NSString stringWithFormat:@"set%@",key.capitalizedString];
    56 //        
    57 //        if ([flag respondsToSelector:@selector(funcName)]) {
    58 //            
    59 //            [flag setValue:obj forKeyPath:key];
    60 //            
    61 //        }
    62 //    }];
    63     
    64     
    65     
    66     
    67     return flag;
    68 }
    69 
    70 
    71 - (void)setIcon:(NSString *)icon
    72 {
    73 //    NSLog(@"%s",__func__);
    74     _icon = [UIImage imageNamed:icon];
    75 }
    76 
    77 // 遍历字典里面所有的key
    78 
    79 //  key:name
    80 //  就去模型中查找有没有setName:,直接调用这个对象setName:赋值
    81 //  假如没有找到setName:。就会去模型中查找有没有_name属性,_name = value
    82 //  假如没有找到_name,还会去模型中查找name属性
    83 //  最终没有找到,就会直接报错。
    84 
    85 
    86 @end
    模型
     1 //
     2 //  XMGFlagView.h
     3 //  03-国旗选择
     4 //
     5 //  Created by xiaomage on 15/6/9.
     6 //  Copyright (c) 2015年 xiaomage. All rights reserved.
     7 //
     8 
     9 #import <UIKit/UIKit.h>
    10 @class XMGFlag;
    11 @interface XMGFlagView : UIView
    12 
    13 @property (nonatomic, strong) XMGFlag *flag;
    14 
    15 @end
    16 
    17 
    18 //
    19 //  XMGFlagView.m
    20 //  03-国旗选择
    21 //
    22 //  Created by xiaomage on 15/6/9.
    23 //  Copyright (c) 2015年 xiaomage. All rights reserved.
    24 //
    25 #import "XMGFlag.h"
    26 #import "XMGFlagView.h"
    27 
    28 @interface XMGFlagView ()
    29 @property (weak, nonatomic) IBOutlet UIImageView *imageView;
    30 @property (weak, nonatomic) IBOutlet UILabel *label;
    31 
    32 @end
    33 
    34 @implementation XMGFlagView
    35 
    36 
    37 - (void)setFlag:(XMGFlag *)flag
    38 {
    39     _flag = flag;
    40     
    41     // 给子控件赋值
    42     _label.text = flag.name;
    43     _imageView.image = flag.icon;
    44 }
    45 /*
    46 // Only override drawRect: if you perform custom drawing.
    47 // An empty implementation adversely affects performance during animation.
    48 - (void)drawRect:(CGRect)rect {
    49     // Drawing code
    50 }
    51 */
    52 
    53 @end
    view
     1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
     2 <document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="8191" systemVersion="15A284" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
     3     <dependencies>
     4         <deployment identifier="iOS"/>
     5         <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="8154"/>
     6     </dependencies>
     7     <objects>
     8         <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
     9         <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
    10         <view contentMode="scaleToFill" id="YWJ-6W-ap9" customClass="XMGFlagView">
    11             <rect key="frame" x="0.0" y="0.0" width="375" height="60"/>
    12             <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
    13             <subviews>
    14                 <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">
    15                     <rect key="frame" x="0.0" y="0.0" width="90" height="60"/>
    16                     <animations/>
    17                     <fontDescription key="fontDescription" type="system" pointSize="17"/>
    18                     <color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
    19                     <nil key="highlightedColor"/>
    20                 </label>
    21                 <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="LkB-3T-KX7">
    22                     <rect key="frame" x="278" y="0.0" width="102" height="65"/>
    23                     <animations/>
    24                 </imageView>
    25             </subviews>
    26             <animations/>
    27             <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
    28             <nil key="simulatedStatusBarMetrics"/>
    29             <freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
    30             <connections>
    31                 <outlet property="imageView" destination="LkB-3T-KX7" id="NPy-qW-igD"/>
    32                 <outlet property="label" destination="bla-Fq-tBg" id="FNP-89-PLs"/>
    33             </connections>
    34             <point key="canvasLocation" x="298.5" y="287"/>
    35         </view>
    36     </objects>
    37 </document>
    xib

     生日键盘

     1 //
     2 //  ViewController.m
     3 //  04-键盘处理
     4 //
     5 //  Created by xiaomage on 15/6/9.
     6 //  Copyright (c) 2015年 xiaomage. All rights reserved.
     7 //
     8 
     9 #import "ViewController.h"
    10 
    11 @interface ViewController ()<UITextFieldDelegate>
    12 @property (weak, nonatomic) IBOutlet UITextField *birthdayField;
    13 
    14 @property (nonatomic, weak) UIDatePicker *datePicker;
    15 
    16 @end
    17 
    18 @implementation ViewController
    19 
    20 #pragma mark - UITextFieldDelegate
    21 // 是否允许开始编辑
    22 //- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
    23 //{
    24 //    return NO;
    25 //}
    26 
    27 // 是否允许结束编辑
    28 //- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
    29 //{
    30 //    return NO;
    31 //}
    32 
    33 
    34 // 是否允许用户输入文字
    35 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    36     return NO;
    37 }
    38 
    39 // 文本框开始编辑的时候调用
    40 - (void)textFieldDidBeginEditing:(UITextField *)textField
    41 {
    42     // 给生日文本框赋值
    43     [self dateChange:_datePicker];
    44 }
    45 - (void)viewDidLoad {
    46     [super viewDidLoad];
    47     // Do any additional setup after loading the view, typically from a nib.
    48     _birthdayField.delegate = self;
    49     
    50     // 自定义生日键盘
    51     [self setUpBirthdayKeyboard];
    52 }
    53 
    54 // 自定义生日键盘
    55 - (void)setUpBirthdayKeyboard
    56 {
    57     // 创建UIDatePicker
    58     // 注意:UIDatePicker有默认的尺寸,可以不用设置frame
    59     UIDatePicker *picker = [[UIDatePicker alloc] init];
    60     
    61     _datePicker = picker;
    62     
    63     // 设置地区 zh:中国
    64     picker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
    65     
    66     // 设置日期的模式
    67     picker.datePickerMode = UIDatePickerModeDate;
    68     
    69     // 监听UIDatePicker的滚动
    70     [picker addTarget:self action:@selector(dateChange:) forControlEvents:UIControlEventValueChanged];
    71     
    72     
    73     _birthdayField.inputView = picker;
    74 }
    75 
    76 // 当UIDatePicker滚动的时候调用
    77 // 给生日文本框赋值
    78 - (void)dateChange:(UIDatePicker *)datePicker
    79 {
    80     NSLog(@"%@",datePicker.date);
    81     // 日期转换字符串
    82     
    83     NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    84     
    85     fmt.dateFormat = @"yyyy-MM-dd";
    86     
    87     NSString *dateStr = [fmt stringFromDate:datePicker.date];
    88     
    89     _birthdayField.text = dateStr;
    90 }
    91 
    92 - (void)didReceiveMemoryWarning {
    93     [super didReceiveMemoryWarning];
    94     // Dispose of any resources that can be recreated.
    95 }
    96 
    97 @end
    View Code
  • 相关阅读:
    iOS No such file or directory
    获取图片某点或区域的颜色
    GCD 异步分组执行
    FMDB
    键盘样式风格有关设置
    libc++abi.dylib handler threw exception
    苹果Xcode帮助文档阅读指南2
    面试集锦-常量,const, const 对指针的影响
    支付宝遇到的坑和解决方案
    闲谈
  • 原文地址:https://www.cnblogs.com/jiaozi-li/p/5666550.html
Copyright © 2011-2022 走看看