Multiple Row Selection in UIPickerView

流过昼夜 提交于 2019-11-26 19:55:01

问题


I want to select multiple rows in a UIPickerView, so I had the idea to show my data in a table and add this table as subview to the picker. I have tried this but didn't succeed.

Any suggestions how to do this?


回答1:


the "accepted" UI for multiple selection on the iPhone is to use a UITableView with checkmarks (i.e. don't use UIPickerView for multiple selection).

However, if you must, there are instructions on how to fake it here http://www.iphonedevsdk.com/forum/iphone-sdk-development/14634-uipickerview-multiple-selection.html by making an empty picker and putting a table view over the top of it.




回答2:


You can do it without UITableView, using just UITapGestureRecognizer :)

Also, add NSMutableArray *selectedItems somewhere in your .h file.

- (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)];
        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 = [datasource objectAtIndex:row];
    cell.tag = row;

    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];
    }
}



回答3:


Implemented a quick hack to get the UIPickerView multiple-selection-behavior (like in Mobile Safari) without adding other views in front of the pickerview, if anyone's interested: https://github.com/alexleutgoeb/ALPickerView

Improvements are highly appreciated!




回答4:


The following code works for iOS 10. I didn't have the chance to test it on older versions but I think it should work. The idea is similar to @suda's one but it adds a single tap recognizer directly to the picker view instead of adding the tap recognizer to each row, as this does not work on iOS7+.

For brevity, I did not include the complete implementation of the UIPickerViewDataSource and UIPickerViewDelegate protocols, only the relevant parts to implement the multiple selection.

// 1. Conform to UIGestureRecognizerDelegate protocol
@interface MyViewController () <UIPickerViewDataSource, UIPickerViewDelegate, UIGestureRecognizerDelegate>

@property (nonatomic, strong) NSMutableArray *selectedArray;    // To store which rows are selected
@property (nonatomic, strong) NSArray *dataArray;           // Picker data
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;

@end

@implementation MyViewController

- (void)viewDidLoad 
{    
    [super viewDidLoad];

    self.selectedArray = [NSMutableArray array]; 
    self.dataArray = @[@"Option 1", @"Option 2", @"Option 3", @"Option 4"];

    // 2. Add tap recognizer to your picker view
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickerTapped:)];
    tapRecognizer.delegate = self;
    [self.pickerView addGestureRecognizer:tapRecognizer];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return true;
}

- (void)pickerTapped:(UITapGestureRecognizer *)tapRecognizer
{
    // 3. Find out wich row was tapped (idea based on https://stackoverflow.com/a/25719326) 
    if (tapRecognizer.state == UIGestureRecognizerStateEnded) {
        CGFloat rowHeight = [self.pickerView rowSizeForComponent:0].height;
        CGRect selectedRowFrame = CGRectInset(self.pickerView.bounds, 0.0, (CGRectGetHeight(self.pickerView.frame) - rowHeight) / 2.0 );
        BOOL userTappedOnSelectedRow = (CGRectContainsPoint(selectedRowFrame, [tapRecognizer locationInView:self.pickerView]));
        if (userTappedOnSelectedRow) {
            NSInteger selectedRow = [self.pickerView selectedRowInComponent:0];
            NSUInteger index = [self.selectedArray indexOfObject:[NSNumber numberWithInteger:selectedRow]];

            if (index != NSNotFound) {
                NSLog(@"Row %ld OFF", (long)selectedRow);
                [self.selectedArray removeObjectAtIndex:index];
            } else {
                NSLog(@"Row %ld ON",  (long)selectedRow);
                [self.selectedArray addObject:[NSNumber numberWithInteger:selectedRow]];
            }
            // I don't know why calling reloadAllComponents sometimes scrolls to the first row
            //[self.pickerView reloadAllComponents];
            // This workaround seems to work correctly:
            self.pickerView.dataSource = self;            
            NSLog(@"Rows reloaded");
        }
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view 
{    
    // 4. Customize your Picker row as needed. 
    // This is a very simple view just to make the point

    UILabel *pickerLabel = (UILabel *)view;

    if (pickerLabel == nil) {
        pickerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 400, 32)];
    }

    BOOL isSelected = [self.selectedArray indexOfObject:[NSNumber numberWithInteger:row]] != NSNotFound;
    NSString *text = [self.dataArray objectAtIndex:row];
    text = [text stringByAppendingString:isSelected ? @"☒ " : @"☐ "];
    [pickerLabel setText:text];

    return pickerLabel;
}


// Do not forget to add the remaining methods to conform the UIPickerViewDataSource and UIPickerViewDelegate protocols!

@end



回答5:


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer 
{
       return true;
}

And you need to override this method,other else form ios9, tap gesture recognization wouldn't work.




回答6:


same resolve in swift 4 for this case

  //set up tap gesture
        let tapGestureRecognaizer = UITapGestureRecognizer(target: self, action: #selector(pickerTapp))
        tapGestureRecognaizer.delegate = self
        tapGestureRecognaizer.numberOfTapsRequired = 2
        self.pickerView.addGestureRecognizer(tapGestureRecognaizer)

@objc func pickerTapp(tapGesture: UITapGestureRecognizer) {
    if tapGesture.state == .ended {
        // looking for frame selection row
        let selectedItem = dataSource2[pickerView.selectedRow(inComponent: 1)]
        let rowHeight = self.pickerView.rowSize(forComponent: 1).height
        let rowWidth = self.pickerView.rowSize(forComponent: 1).width
        let selectRowFrame = CGRect(x: CGFloat(Int(self.pickerView.frame.width) / self.pickerView.numberOfComponents), y: (self.pickerView.frame.height - rowHeight) / 2, width: rowWidth, height: rowHeight)

        let userTappedOnSelectedRow = selectRowFrame.contains(tapGesture.location(in: self.pickerView))
        // if tap to selection row ....
        if userTappedOnSelectedRow {
            if selectedArray.contains(selectedItem) {
                var index = 0
                for item in selectedArray {
                    if item == selectedItem {
                        selectedArray.remove(at: index)
                    } else {
                        index += 1
                    }
                }
            } else {
                selectedArray.append(selectedItem)
            }
        }

        //reload Data
        self.pickerView.dataSource = self
        self.pickerView.selectRow(selectedRow, inComponent: 1, animated: false)
        self.pickerView(self.pickerView, didSelectRow: selectedRow, inComponent: 1)
    }

full resolve: https://github.com/akonoplev/Features/blob/master/MultiSelectUIPickerView/MultiSelectUIPickerView/ViewController.swift




回答7:


Here's my take on this problem: https://github.com/aselivanov/UIMultiPicker. I wanted exactly the same picker as mobile Safari uses to handle <select multiple>. It looks very similar to UIPickerView (I bet they share same code).



来源:https://stackoverflow.com/questions/2903004/multiple-row-selection-in-uipickerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!