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

(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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值