码迷,mamicode.com
首页 > 移动开发 > 详细

iOS开发技巧 - 使用UIPickerView来选择值

时间:2016-08-15 18:38:27      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:

(Swift)

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource {
    var picker: UIPickerView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        picker = UIPickerView()
        
        // select the current view controller as the data source of the picker view
        picker.dataSource = self
        picker!.delegate = self
        
        picker.center = view.center
        view.addSubview(picker)
    }
    
    /*
        Implemented some of the methods of the UIPickerViewDataSource protocol
    */
    
    // returns the number of ‘columns‘ to display
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        if pickerView == picker {
            return 1
        }
        return 0
    }
    
    // returns the number of rows in each component
    func pickerView(pickerView: UIPickerView,
        numberOfRowsInComponent component: Int) -> Int {
        if pickerView == picker {
            return 10
        }
        return 0
    }
}

func pickerView(pickerView: UIPickerView,
    titleForRow row: Int,
    forComponent component: Int) -> String! {
    return "\(row + 1)"
}

 

(Objective-C)

@interface ViewController () <UIPickerViewDataSource, UIPickerViewDelegate>

@property (nonatomic, strong) UIPickerView *myPicker;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.myPicker = [[UIPickerView alloc] init];
    
    // select the current view controller as the data source of the picker view
    self.myPicker.dataSource = self;
    self.myPicker.delegate = self;
    
    self.myPicker.center = self.view.center;
    [self.view addSubview:self.myPicker];
}

/*
    Implemented some of the methods of the UIPickerViewDataSource protocol
*/

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    if ([pickerView isEqual:self.myPicker]){
        return 1;
    }
    return 0;
}
- (NSInteger) pickerView:(UIPickerView *)pickerView
    numberOfRowsInComponent:(NSInteger)component {
    if ([pickerView isEqual:self.myPicker]){
        return 10;
    }
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView
    titleForRow:(NSInteger)row
    forComponent:(NSInteger)component {
    if ([pickerView isEqual:self.myPicker]) {
        /* Row is zero-based and we want the first row (with index 0)
        to be rendered as Row 1, so we have to +1 every row index */
        
        return [NSString stringWithFormat:@"Row %ld", (long)row + 1];
    }
    
    return nil;
}

 

iOS开发技巧 - 使用UIPickerView来选择值

标签:

原文地址:http://www.cnblogs.com/davidgu/p/5773764.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!