我在项目的不同部分实现了几个UIPickerView。大多数人都做得很好。然而,最新的一个有一些非常奇怪的行为,很难描述。简而言之,有2个异常:
pickerView:rowHeightForComponent:
方法时,不会发生此问题。)实施相当简单,类似于我在其他地方所做的,所以我无法弄清楚我做错了什么。数据源使用简单的数组,并且日志记录显示它正常工作。即使是在屏幕上没有显示任何值的选择器的初始显示,也会根据NSLog
行正确记录值。事实上,它的记录与第二次调用完全相同,在第二次调用中它正确显示值(在滚动之前使它们消失)。
“库”栏按钮调用以下操作,以便使用UIPickerView作为输入配置UITextField,然后使该文本字段成为第一个响应者:
- (IBAction)selectStyleFromLibrary:(id)sender {
_dummyPickerField = [[UITextField alloc] init];
[self.view insertSubview:_dummyPickerField atIndex:0];
StylesController *stylesLibrary = [[StylesController alloc] init];
[stylesLibrary getStyles];
UIPickerView *libraryPicker = [[UIPickerView alloc] init];
libraryPicker.delegate = stylesLibrary;
libraryPicker.dataSource = stylesLibrary;
_dummyPickerField.inputView = libraryPicker;
[_dummyPickerField becomeFirstResponder];
}
所有选择器视图的委托和数据源方法都是:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return styleKeys.count;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
return 64;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
NSLog(@"%@", styleKeys[row]);
return styleKeys[row];
}
为什么这种行为不正常?
更新:我还尝试使用简单的现有文本字段,而不是动态创建一个。它没有帮助。
答案 0 :(得分:2)
以下是我如何解决它(从@dip评论中获得一些灵感)......
我的数据源/委托对象是一个单独的对象,它没有被明确地保留在任何地方,所以我现在重新安排了一些东西,使它成为一个属性,并在viewDidLoad中分配它,以便它坚持下去。 / p>
我猜UIPickerView只有一个弱引用(或两个弱引用),这当然不足以让它长时间提供数据和委托。
所以现在我有以下内容(不包括实际的委托和数据源方法):
@property (nonatomic, strong) StylesController *stylesLibrary;
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Metal Tile Very Light"]];
self.editor = (StyleEditor *)self.tabBarController;
if ( ! self.editor.namedStyle ) {
nameField.borderStyle = UITextBorderStyleNone;
nameField.userInteractionEnabled = NO;
}
_stylesLibrary = [[StylesController alloc] init];
[_stylesLibrary getStyles];
}
- (IBAction)selectStyleFromLibrary:(id)sender {
_dummyPickerField = [[UITextField alloc] init];
[self.view insertSubview:_dummyPickerField atIndex:0];
UIPickerView *libraryPicker = [[UIPickerView alloc] init];
libraryPicker.delegate = _stylesLibrary;
libraryPicker.dataSource = _stylesLibrary;
_dummyPickerField.inputView = libraryPicker;
_dummyPickerField.inputAccessoryView = [self accessoryViewWithText:@"Done" target:self action:@selector(libraryPickerDone) forField:_dummyPickerField];
[_dummyPickerField becomeFirstResponder];
}