我正在尝试使用UIPicker
中的setAccessoryType
和Suda's blog
UITableViewCell
在UITapGestureRecognizer
中实施多选选项
现在问题是: 没有收到任何错误,但toggleSelection:
未被识别。
selectedItems
未被调用(无法在#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource>
{
NSMutableArray *selectedItems;
NSArray *datasource;
}
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@end
中添加/删除对象。)
我在SO中搜索过这个问题,但没有得到任何解决方案。没有什么对我有用。
我使用了以下代码
ViewController.h
- (void)viewDidLoad {
[super viewDidLoad];
datasource = [[NSArray alloc] initWithObjects:@"A", @"B", @"C", @"D", @"E", nil];
self.pickerView.delegate = self;
self.pickerView.dataSource = self;
selectedItems = [[NSMutableArray alloc] init];
}
-(NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return datasource.count;
}
-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return datasource[row];
}
- (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 setUserInteractionEnabled:YES];
[cell addGestureRecognizer:singleTapGestureRecognizer];
// Also tried with [cell.contentView addGestureRecognizer:singleTapGestureRecognizer];
}
if ([selectedItems indexOfObject:[NSNumber numberWithInt:row]] != NSNotFound) {
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
} else {
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
cell.textLabel.text = [datasource objectAtIndex: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];
}
}
ViewController.m
intellij
任何帮助都会很明显。