我在網上發現了這個代碼,並且驚訝地發現它基本上和我想要的完全相反。以下是方法...在UIPickerView中選擇多個元素
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
UITableViewCell *cell = (UITableViewCell *)view;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
[cell setBackgroundColor:[UIColor clearColor]];
[cell setBounds: CGRectMake(0, 0, cell.frame.size.width -20 , 44)];
cell.tag = row;
UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleSelection:)];
singleTapGestureRecognizer.numberOfTapsRequired = 1;
[cell addGestureRecognizer:singleTapGestureRecognizer];
}
if ([selectedItems indexOfObject:[NSNumber numberWithInt:row]] != NSNotFound) {
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
} else {
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
cell.textLabel.text = @"Joe";
return cell;
}
- (void)toggleSelection:(UITapGestureRecognizer *)recognizer {
NSNumber *row = [NSNumber numberWithInt:recognizer.view.tag];
NSUInteger index = [selectedItems indexOfObject:row];
if (index != NSNotFound) {
[selectedItems removeObjectAtIndex:index];
[(UITableViewCell *)(recognizer.view) setAccessoryType:UITableViewCellAccessoryNone];
} else {
[selectedItems addObject:row];
[(UITableViewCell *)(recognizer.view) setAccessoryType:UITableViewCellAccessoryCheckmark];
}
}
結果是每個UIPickerView項目的簡單複選標記。這很棒,但是默認情況下,PickerView的所有元素都被選中,這意味着它們會顯示一個複選標記(除了我在代碼中專門選擇的選項外,我不希望它們被選中)。你可以編輯我的方法,並試圖找出如何做我在做什麼。
另外我怎麼能夠看到用戶在我的代碼中選擇的元素。幫幫我!
如果你已經寫得很好,你可以給我示例代碼來實現。我有同樣的需要 – iEinstein 2013-05-30 15:21:05