可以在UIPickerView中有多个选定的选项吗?
例如,var array = [1,2,3,4,5]
在UIPickerView中同时选择[1,3,5]
且UIPickerView中只有一个部分。
提前谢谢。
答案 0 :(得分:0)
好的control完全相同。
还有一些方法可以使用UITapGestureRecognizer。
目标C
- (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];
}
}
Swift
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView) -> UIView {
var cell: UITableViewCell = view
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyleDefault, reuseIdentifier: nil)
cell.setBackgroundColor(UIColor.clearColor())
cell.setBounds(CGRectMake(0, 0, cell.frame.size.width - 20, 44))
var singleTapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "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
}
func toggleSelection(recognizer: UITapGestureRecognizer) {
var row: Int = NSNumber.numberWithInt(recognizer.view.tag)
var index: UInt = selectedItems.indexOfObject(row)
if index != NSNotFound {
selectedItems.removeObjectAtIndex(index)
(recognizer.view).setAccessoryType(UITableViewCellAccessoryNone)
}
else {
selectedItems.addObject(row)
(recognizer.view).setAccessoryType(UITableViewCellAccessoryCheckmark)
}
}