如果 UIPickerView 未触及,则 UIPickerView 选择第 0 行
Posted
技术标签:
【中文标题】如果 UIPickerView 未触及,则 UIPickerView 选择第 0 行【英文标题】:UIPickerView selecting row zero if PickerView not touched 【发布时间】:2013-04-04 15:43:18 【问题描述】:我试图消除的关于 PickerView 的一个烦人的事情是,如果用户必须从第 0 行移开并重新打开以选择它。我希望这样,如果用户决定选择第 0 行,他只需按下按钮即可转到下一个视图,并且将选择第 0 行值。
有什么想法吗?
非常感谢
这是我的代码 - 目前,如果连接到 saveSelectedCondition 的按钮被按下,并且 pickerView 没有移出第 0 行,则为 selectedCondition 返回 null,而不是第 0 行的条件值:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
Condition *condition = [[self.fetchedResultsController fetchedObjects] objectAtIndex:row];
self.selectedCondition = condition;
NSLog(@"The '%@' condition was selected using the picker", self.selectedCondition.name);
- (IBAction)saveSelectedCondition:(id)sender
[self.selectedCondition setValue:@"YES" forKey:@"isSelectedCondition"];
[self.managedObjectContext save:nil];
NSLog(@"Saving selected condition (%@) with isSelectedCondition set to '%@'", self.selectedCondition.name, self.selectedCondition.isSelectedCondition);
【问题讨论】:
如果用户没有触摸选择器,那么您希望自动选择第 0 行,对吗? 是的,这正是我想做的,我已经在 performFetch 方法中进行了整理 只需在您的 ViewDidLoad 方法中放入单行代码并尝试 [pickerView selectRow:0 inComponent:0 animated:YES];让我知道它是否有效 这里的pickerView是你的pickerview的对象 @Pratik - 感谢您的建议 - 它没有用。但是,我通过设置 PickerView didSelect 打算选择的 Condition 实例来管理解决方法,即 selectedCondition,属性 isSelectedCondition 的键为 YES,用于从 performFetch 出现的索引为零的条件,即 pickerView 中的第 0 行。请参阅下面的我的自我回答。 【参考方案1】:试试看……
- (IBAction)saveSelectedCondition:(id)sender
myText.text = [myArray objectAtIndex:0];//Just add this line for set first value
[self.selectedCondition setValue:@"YES" forKey:@"isSelectedCondition"];
[self.managedObjectContext save:nil];
NSLog(@"Saving selected condition (%@) with isSelectedCondition set to '%@'", self.selectedCondition.name, self.selectedCondition.isSelectedCondition);
Set first value when your picker view called.
【讨论】:
【参考方案2】:我现在使用以下代码在 performFetch 之后对其进行了整理:
[self performFetch];
NSLog(@"The following Conditions were fetched for the Picker by SelectorViewController:");
for (Condition *fetchedCondition in [self.fetchedResultsController fetchedObjects])
if (fetchedCondition ==[[self.fetchedResultsController fetchedObjects] objectAtIndex:0])
[fetchedCondition setValue:@"YES" forKey:@"isSelectedCondition"];
self.selectedCondition = fetchedCondition;
else
[fetchedCondition setValue:@"NO" forKey:@"isSelectedCondition"];
[self.managedObjectContext save:nil];
NSLog(@"Condition: %@, isSelectedCondition %@", fetchedCondition.name, fetchedCondition.isSelectedCondition);
【讨论】:
以上是关于如果 UIPickerView 未触及,则 UIPickerView 选择第 0 行的主要内容,如果未能解决你的问题,请参考以下文章
在 uitableviewcell 中自定义 uipickerview