Skip to content

Instantly share code, notes, and snippets.

@pruinis
Last active August 1, 2016 16:22
Show Gist options
  • Save pruinis/f743b13211d9f4b6d1b2dfe0a4c4b66c to your computer and use it in GitHub Desktop.
Save pruinis/f743b13211d9f4b6d1b2dfe0a4c4b66c to your computer and use it in GitHub Desktop.
UIPicker detect tap / touch on currently selected row
// Obj-C
// GestureRecognizer
UITapGestureRecognizer *tapToSelect = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tappedToSelectRow:)];
tapToSelect.delegate = self;
[self.pickerView addGestureRecognizer:tapToSelect];
#pragma mark - Actions
- (IBAction)tappedToSelectRow:(UITapGestureRecognizer *)tapRecognizer
{
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];
// [self pickerView:self.pickerView didSelectRow:selectedRow inComponent:0];
// .. your action here ..
}
}
}
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return true;
}
// MARK: Swift
// GestureRecognizer
let tapToSelect = UITapGestureRecognizer(target: self, action: #selector(tappedToSelectRow(_:)))
tapToSelect.delegate = self
topicsPicker.addGestureRecognizer(tapToSelect)
// MARK: Actions
func tappedToSelectRow(tapRecognizer: UITapGestureRecognizer) {
if tapRecognizer.state == .Ended {
let rowHeight = topicsPicker.rowSizeForComponent(0).height
let selectedRowFrame = CGRectInset(topicsPicker.bounds, 0, (CGRectGetHeight(topicsPicker.frame) - rowHeight) / 2.0)
let userTappedOnSelectedRow = (CGRectContainsPoint(selectedRowFrame, tapRecognizer.locationInView(topicsPicker)))
if userTappedOnSelectedRow {
// let selectedRow = topicsPicker.selectedRowInComponent(0)
// topicsPicker.selectRow(selectedRow, inComponent: 0, animated: false)
// .. your action here ..
}
}
}
// MARK: UIGestureRecognizerDelegate
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
@pruinis
Copy link
Author

pruinis commented Aug 1, 2016

UIPicker detect tap / touch on currently selected row
from stackoverflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment