<分区>
我正在设置一个 UIPickerView
来选择 choice a、choice b、choice c 和很快。我试图解释 Apple 的示例代码,但对于像我这样的初学者来说,这似乎很难理解。如果可能的话,我还希望选择器 View 中的选择将我带到另一个页面。
<分区>
我正在设置一个 UIPickerView
来选择 choice a、choice b、choice c 和很快。我试图解释 Apple 的示例代码,但对于像我这样的初学者来说,这似乎很难理解。如果可能的话,我还希望选择器 View 中的选择将我带到另一个页面。
最佳答案
对于每个初学者来说,第一次理解这些东西是很乏味的。
无论如何,你知道如何使用 UITableView
吗?你知道如何使用 UITableViewDelegate
和 UITableViewDataSource
吗?如果您的回答是肯定的,那么想象一下 UIPickerView
就像 UITableView
(但请记住它们不是 UITableViewController
)。
比方说,我有一个 UIPickerView
:
UIPickerView *objPickerView = [UIPickerView new]; // You need to set frame or other properties and add to your view...you can either use XIB code...
1) 首先,您需要通过 IB 或代码将 delegate
和 dataSource
分配给 UIPickerView
。这取决于您的实现(所以这一步看起来非常类似于 UITableView
,不是吗?)
像这样:
objPickerView.delegate = self; // Also, can be done from IB, if you're using
objPickerView.dataSource = self;// Also, can be done from IB, if you're using
2) 接下来,您需要定义部分的数量,如下所示:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1; // Or return whatever as you intend
}
2) 然后你需要定义你需要的行数:
- (NSInteger)pickerView:(UIPickerView *)thePickerView
numberOfRowsInComponent:(NSInteger)component {
return 3;//Or, return as suitable for you...normally we use array for dynamic
}
3) 然后,为行定义标题(如果您有多个部分,则为每个部分定义标题):
- (NSString *)pickerView:(UIPickerView *)thePickerView
titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [NSString stringWithFormat:@"Choice-%d",row];//Or, your suitable title; like Choice-a, etc.
}
4) 接下来,你需要在有人点击一个元素时获取事件(因为你想导航到其他 Controller /屏幕):
- (void)pickerView:(UIPickerView *)thePickerView
didSelectRow:(NSInteger)row
inComponent:(NSInteger)component {
//Here, like the table view you can get the each section of each row if you've multiple sections
NSLog(@"Selected Color: %@. Index of selected color: %i",
[arrayColors objectAtIndex:row], row);
//Now, if you want to navigate then;
// Say, OtherViewController is the controller, where you want to navigate:
OtherViewController *objOtherViewController = [OtherViewController new];
[self.navigationController pushViewController:objOtherViewController animated:YES];
}
这就是您需要的所有实现。
关于objective-c - 我将如何设置 UIPickerView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13756591/