objective-c 在 UIPickerView 中为每个组件获取选定的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1389771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get selected row in UIPickerView for each component
提问by Dave DeLong
I have an UIPickerViewwith 3 components populated with 2 NSMutableArrays(2 components have the same array).
我有一个UIPickerView3 个组件,其中填充了 2 个NSMutableArrays(2 个组件具有相同的数组)。
A tutorial says:
一个教程说:
//PickerViewController.m
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSLog(@"Selected Color: %@. Index of selected color: %i", [arrayColors objectAtIndex:row], row);
}
But I want to show the selected row for each component in an UIAlertViewafter the user touched an UIButton.
但我想UIAlertView在用户触摸 UIButton 后显示每个组件的选定行。
Is there a way to do this? Or must I just use 3 invisible UILabelsas buffer?
有没有办法做到这一点?或者我必须只使用 3 invisibleUILabels作为缓冲区?
Thanks in advance.
提前致谢。
回答by Dave DeLong
So, in your button action method, you can do something like this:
因此,在您的按钮操作方法中,您可以执行以下操作:
- (IBAction) showAlert {
NSUInteger numComponents = [[myPickerView datasource] numberOfComponentsInPickerView:myPickerView];
NSMutableString * text = [NSMutableString string];
for(NSUInteger i = 0; i < numComponents; ++i) {
NSUInteger selectedRow = [myPickerView selectedRowInComponent:i];
NSString * title = [[myPickerView delegate] pickerView:myPickerView titleForRow:selectedRow forComponent:i];
[text appendFormat:@"Selected item \"%@\" in component %lu\n", title, i];
}
NSLog(@"%@", text);
}
This would be the absolute formal way to retrieve information (by using the proper datasource and delegate methods), but it might be easier (depending on your set up), to just grab the selected row and then pull the information out of your model directly, instead of going through the delegate method.
这将是检索信息的绝对正式方式(通过使用适当的数据源和委托方法),但它可能更容易(取决于您的设置),只需获取选定的行,然后直接从模型中提取信息,而不是通过委托方法。
回答by Roman Barzyczak
Swift 3 version:
斯威夫特 3 版本:
var value = ""
for i in 0..<numberOfComponents {
let selectedRow = pickerView.selectedRow(inComponent: i)
if let s = pickerView.delegate?.pickerView!(pickerView, titleForRow: selectedRow, forComponent: i) {
value += s
}
}

