我的 viewController 中有几个 UIPickerView。
这是其中之一需要自定义,因为它在 1 个选择器行中显示 2 个 UILabels。
我使用这些委托(delegate)方法:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row
forComponent:(NSInteger)component {
// this method is use for normal pickers, and I would judge whether the picker that calling
// this method is a normal one or the special one by pickerView.
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row
forComponent:(NSInteger)component reusingView:(UIView *)view {
// and this one is specially for the special picker, I would also judge the pickerView is
//normal or special, if pickerView is normal, return nil, else I return a UIView with
//2 UIlabels.
}
但是现在经过我的调试,我发现如果我同时实现这两个方法,第二个方法总是被调用,而第一个方法似乎永远不会被调用,
这导致我的特殊选择器显示正确的数据,但其他选择器什么也没有。
我怎样才能做到这一点?
如果我在第二种方法中给出所有选择器的数据,那么reusingView是否会成为问题,因为特殊选择器的reusingView与其他选择器的格式不同?
非常感谢!
最佳答案
使用不同的委托(delegate)并不是那么简单。创建一个单独的类,
@interface MyCustomDelegate : NSObject <UIPickerViewDelegate>
并实现委托(delegate)方法,在本例中
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row
forComponent:(NSInteger)component {
// this method is use for normal pickers, and I would judge whether the picker that calling
// this method is a normal one or the special one by pickerView.
}
完成此操作后,创建此类的实例并将其设置为委托(delegate),例如..
pickerView.delegate = [[MyCustomDelegate alloc] initWithData:data] autorelease];
其中的数据可能是您可能想要包含在标题的委托(delegate)方法中使用的数据。
您可以为所有选择器使用相同的委托(delegate)实例,也可以创建单独的实例。这在很大程度上取决于您拥有的数据类型。如果它们彼此无关,那么最好使用单独的实例,否则您可以只使用一个实例。
嗯,就是这样。
<小时/>至于第二个, 你会做这样的事情
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
if (pickerView==specialPickerView) {
}
else {
UILabel *lbl = [[UILabel alloc] init];
lbl.text = [self pickerView:pickerView titleForRow:row forComponent:component];
//do some more styling like setting up the font as bold
//adding some padding to the text and some shiny things
return lbl;
}
}
当然,您可以在现有的类(class)中执行此操作。
关于ios - 几个UIPickerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9393612/