(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; }
时间: 2024-10-14 21:28:30