zoukankan      html  css  js  c++  java
  • UIPickerView

    UIPickerView控件也是iPhone中比较常用到的一个控件,它通过转轮界面提供一系列多值选项,它向用户显示信息,也收集用户输入。下面就是一个普通的UIPickerView控件。

    UIPickerView里面的组件数和组件里的内容都是由我们在代码里面定制的。要使用UIPickerView就要遵守两种协议,一个是UIPickerViewDelegate,另一种是UIPickerViewDataSource。在iPhone开发中,我们经常会听到协议这个词,协议定义了一组方法,有些方法是必须实现的,有些方法是可选的,就要看你要实现的功能了,通俗点讲,协议就相当一个合同,规定了我们要做什么。

    UIPickerViewDelegate协议必须实现的方法有:

    pickerView: titleForRow:forComponent,这个方法根据指定的行号返回该行的标题,也就是向用户显示的字符串。

    UIPickerViewDataSource协议必须实现的方法有:

    1.numberOfComponentsInPickerView,这个方法返回UIPickerView需要多少个组件。

    2.pickerView: numberOfRowsInComponent,这个方法返回指定组件包含多少行。

    建立一个名为InstaEmail的项目,在InstaEmailViewController.h里代码如下:

    #import <UIKit/UIKit.h>
    
    @interface InstaEmailViewController : UIViewController <UIPickerViewDataSource,UIPickerViewDelegate>{
        NSArray *activities_;
        NSArray *feelings_;
    }
    
    @end
    

     在InstaEmailViewController.m里实现两种协议所必须的方法,代码如下:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        activities_=[[NSArray alloc]initWithObjects:@"sleeping",@"eating",@"working",@"thinking",
                     @"crying",@"begging",@"leaving",@"shopping",@"hello worlding", nil];
        feelings_=[[NSArray alloc]initWithObjects:@"awesome",@"sad",@"happy",@"ambivalent",@"nauseous",
                   @"psyched",@"confused",@"hopeful",@"anxious", nil];
    }
    
    #pragma mark -
    #pragma mark Picker Datasource Protocol
    
    //返回显示的列数
    -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
        return 2;
    }
    
    //返回当前列显示的行数
    -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
        if(component==0){
            return [activities_ count];
        }else{
            return [feelings_ count];
        }
    }
    
    #pragma mark -
    #pragma mark Picker Delegate Protocol
    
    //设置当前行的内容
    -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
        if(component==0){
            return [activities_ objectAtIndex:row];
        }
        else{
            return [feelings_ objectAtIndex:row];
        }
        return nil;
    }
    

     项目运行起来,截图如上。

  • 相关阅读:
    短视频不为人知的素材来源 以及平台推荐的黑盒机制
    说什么月入几万 我是不是应该一头撞死?
    Python 3 进阶 —— 使用 PyMySQL 操作 MySQL
    CentOS安装Subversion 1.9.*版本客户端
    [算法]PHP随机合并数组并保持原排序
    CentOS安装Memcached
    Git Windows客户端保存用户名和密码
    ApiGen 4.0配置项
    ApiGen安装
    SQL服务器模式
  • 原文地址:https://www.cnblogs.com/hxxy2003/p/2271815.html
Copyright © 2011-2022 走看看