I am trying to design a view which contains a list of items to be ordered and placed into an array. The items are dynamically generated and thus cold be an amount that goes off the bottom of the screen.
For this reason my first view is a UIScrollview which takes the whole devices screen
Nested under this I have a label, explaining what the list is for and how to interact with it and then a UITableView with drag & drop with the delegate methods from http://b2cloud.com.au/how-to-guides/reordering-a-uitableviewcell-from-any-touch-point
The problem I am facing is that while the script works great when there are 1 or two rows, when the contentsize of the UIscrollview is larger than the screen it seems to take priority over the drag & drop leading to unpredictable behaviour.
Is there any way to make clicks on the table take priority to only edit the cells and allow the user to scroll by interacting elsewhere on the view?
Thanks
UPDATE
Based on the comment below I managed to get:
- (void)viewDidLoad
{
[super viewDidLoad];
//
//
//
UIPanGestureRecognizer *tapGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(wasPanned:)];
[self.view addGestureRecognizer:tapGesture];
}
-(void)wasPanned:(UIPanGestureRecognizer *)gesture
{
CGPoint point = [gesture locationInView:scrollView];
UIView *isTable = [scrollView hitTest:point withEvent:nil];
if (gesture.state == UIGestureRecognizerStateBegan)
{
if([[[isTable class] description] isEqualToString:#"UITableViewCellReorderControl"])
{
NSLog(#"Dragged from within table");
[scrollView setScrollEnabled: NO];
}
else
{
[scrollView setScrollEnabled:YES];
}
}
else{
[scrollView setScrollEnabled:YES];
}
}
Now, when the scrollview is not long enough to begin scrolling it NSLogs the message fine
However when the scrollview is longer it only recognises the gesture if the scrollview hasn't began scrolling first
Update
I now have the Console recognising touches in the table 100% of the time and disable scrolling. Disabling the scrolling however also stops the drag & drop functionality. Does anyone know why?
Extra code:
tapGesture.delegate = self;
#pragma mark UIGestureRecognizerDelegate
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
So my final (but not perfect) solution was to do this:
.h
<UIGestureRecognizerDelegate>
.m (viewDidLoad)
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(wasTapped:)];
[self.view addGestureRecognizer:tapGesture];
tapGesture.delegate = self;
.m
-(void)wasTapped:(UIPanGestureRecognizer *)gesture
{
CGPoint point = [gesture locationInView:scrollView];
UIView *isTable = [scrollView hitTest:point withEvent:nil];
if (gesture.state == UIGestureRecognizerStateBegan)
{
if([[[isTable class] description] isEqualToString:#"UITableViewCellReorderControl"])
{
NSLog(#"Dragged from within table");
[scrollView setScrollEnabled: NO];
}
else
{
[scrollView setScrollEnabled:YES];
}
}
else{
[scrollView setScrollEnabled:YES];
}
}
A tap gesture works better than a Pan gesture because a pan gesture seems to recognise press&hold, drag, stop, drag as two different gestures. The feature now works as it should but if you so much as move your finger before the animation for a cell moving has started it will scroll. You also have to wait for the view (can I call it overscroll?) animation to completely stop and the scrollbars disappear before it will grab cells.
I'd appreciate it if anyone can improve on it :)
Related
I am using UITapGestureRecognizer for detecting which UIView was tapped on my screen but for some reason it only detects the parent view tap, for example below code logs only parent views tag. How do i detect subview taps which are present on main view. Please suggest.
Inside View did load :-
UITapGestureRecognizer *viewTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(actionForViewTapped:)];
[self.view addGestureRecognizer:viewTapRecognizer];
Method outside view did load.
-(void) actionForViewTapped:(UITapGestureRecognizer*)sender {
NSLog(#"view tapped");
UIView *view = sender.view;
NSLog(#"view tag is %lu", view.tag); //Always prints parent view tag.
if(view.tag == 10){
NSLog(#"tag1 tapped"); //Not called
}
if(view.tag == 20){
NSLog(#"tag 2 tapped"); //Not called
}
}
We have more options to find detecting on sub view by tap gesture
CHOICE 1:Directly tap to SubView
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapSubView)];
tapGesture.numberOfTapsRequired = 1;
[subView addGestureRecognizer:tapGesture];
CHOICE 2:Finding tap on SubView through Parent View
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapSubView)];
tapGesture.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:tapGesture];
-(void)tapSubView:(UITapGestureRecognizer *)sender
{
UIView* view = sender.view;
CGPoint loc = [sender locationInView:view];
UIView* subview = [view hitTest:loc withEvent:nil];
//OR
CGPoint point = [sender locationInView:sender.view];
UIView *viewTouched = [sender.view hitTest:point withEvent:nil];
if ([viewTouched isKindOfClass:[self.view class]])
{
NSLog(#"the subView is called");
}
else
{
NSLog(#"the subView is not called");
}
}
Printed Output is
the subView is called
CHOICE 3:Find Tap Detection using Delegate methods of Gesture
First You have to add the GestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if([touch.view isKindOfClass: [self.view class]] == YES)
{
return YES; // return YES (the default) to allow the gesture recognizer to examine the touch object
}
else {
return NO; //NO to prevent the gesture recognizer from seeing this touch object.
}
}
The gesture recognizer is only associated with one specific view, which means it will only recognize touches on the view it is added to. If you want to know which subview was touched, then you will need to do a couple of things:
Set userInteractionEnabled = false for each subview. This will make it so that every touch on a subview is passed up to the parent view, and the touch will be recognized by the gesture recognizer.
There isn't enough information on your view hierarchy or layout to know exactly how to proceed from here, but you can use one or some of these methods to determine which view was touched: UIView.hitTest(_:with:), UIView.point(inside:with:), CGRectContainsPoint() or UIGestureRecognizer.location(in:). For example, if the subviews do not overlap each other, you could use the following code snippet to test if the touch was in a particular view:
let location = tapGesture.locationInView(parentView)
if CGRectContainsPoint(subview1, location) {
// subview1 was touched
}
I have a UIView with a UITextField, UIButton and UITable view. The textfield and button compromise a search bar and the results are then loaded into the table view.
I'd like to make it so they keyboard dismisses. If the user taps something when they are editing the text field. My strategy would be to add a gesture recognizer to the UIView, but then gesture recognizer seems to intercept all the touches from the table view and you |tableView:didSelectCellAtIndexPath:| never gets called. Whats interesting (to me at least) is that the UIButton is still tap-able when the user is editing the field even though the UITableView isn't.
I've tried implementing |gestureRecognizer::shouldRecognizeSimultaneouslyWithGestureRecognizer:| to alway return yes, but that doesn't help. I've also tried setting
singleTapRecognizer.cancelsTouchesInView = NO;
which also doesn't help.
I'm happy with the idea of adding and removing the gesture recognizer when the text field calls |textFieldDidBeginEditing:| and |textFieldDidFinishEditing:|, though this feels messy and it still takes two taps to touch a cell when you're editing the text field (one to dismiss they keyboard and remove the recognizer, and one to tap the cell).
Is there a better way?
Relevant code below:
- (void)loadView {
[super loadView];
self.scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.scrollView.backgroundColor = [FDEColors viewBackgroundColor];
self.view = self.scrollView;
self.searchField = [[UITextField alloc] initWithFrame:CGRectZero];
self.searchField.placeholder = #"What are you looking for?";
self.searchField.backgroundColor = [FDEColors textFieldBackgroundColor];
self.searchField.clipsToBounds = YES;
self.searchField.layer.borderColor = [[FDEColors buttonColor] CGColor];
self.searchField.layer.borderWidth = 1.f;
self.searchField.returnKeyType = UIReturnKeySearch;
self.searchField.delegate = self;
[self.view addSubview:self.searchField];
self.searchButton = [[UIButton alloc] initWithFrame:CGRectZero];
self.searchButton.backgroundColor = [FDEColors buttonColor];
[self.searchButton setTitle:#"Search" forState:UIControlStateNormal];
[self.searchButton addTarget:self
action:#selector(searchPressed:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.searchButton];
self.resultsTableView =
[[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
self.resultsTableView.delegate = self;
self.resultsTableView.dataSource = self;
self.resultsTableView.backgroundColor = [FDEColors viewBackgroundColor];
[self.resultsTableView setSeparatorInset:UIEdgeInsetsZero];
self.resultsTableView.layoutMargins = UIEdgeInsetsZero;
[self.resultsTableView registerClass:[FDESearchResultsCell class]
forCellReuseIdentifier:[FDESearchResultsCell reuseIdentifier]];
[self.view addSubview:self.resultsTableView];
self.singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(dismissKeyboard)];
[self.view addGestureRecognizer:self.singleTapRecognizer];
}
- (void)dismissKeyboard {
[[self view] endEditing:YES];
}
Try implementing the gesture recognizer's delegate method:
- (BOOL) gestureRecognizer:ShouldReceiveRouch:
In this method, check for the touch's location. If it's inside the tableview, return no, so the tableview can receive the touch. Otherwise, return YES and let the recognizer handle the touch.
Edit: As for the button receiving the touch despite the recognizer's existence, as of iOS6 Apple decided to give buttons and some other controls priority when it comes to recognizing gestures. It only applies to antagonizing gestures though, in your case a single tap. If for example you also had a pan recognizer, the recognizer would have precedence, not the button.
Edit 2:
An example implementation of the method mentioned above:
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
// Determine if the touch is inside the custom subview
if ([touch view] == self.yourTableView){
// If it is, prevent all of the delegate's gesture recognizers
// from receiving the touch
return NO;
}
return YES;
}
I have a UIImageView that I am trying to move using a UIPanGestureRecognizer object. The UIImageView is positioned over top of a UITableView, and serves as a scrollbar. I want this UIImageView to be moved by the user up or down the UITableView, not sideways. To accomplish this, I have implemented UIGestureRecognizerDelegate, and I have the following methods:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
- (void)panGestureDetected:(UIPanGestureRecognizer *)recognizer {
NSLog(#"Do I get called?");
//_startLocation is a property of type CGPoint that I declare in the .h file
_startLocation = [recognizer locationInView:_imageView];
NSLog(#"The point is: %d", _startLocation);
CGRect frame = [_imageView frame];
frame.origin.y += frame.origin.y - _startLocation.y;
[_imageView setFrame: frame];
_imageView.center = _startLocation;
}
The method, panGestureDetected is called from viewDidLoad as follows:
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(panGestureDetected:)];
panGesture.maximumNumberOfTouches = 1;
panGesture.minimumNumberOfTouches = 1;
panGesture.delegate = self;
[_table addGestureRecognizer:panGesture];
Unfortunately, my UIImageView moves all over the place frantically on the screen when I try to move it. I want to see a smooth scrolling UIImageView go up/down while the user drags it. Can anyone see what I am doing wrong?
In your handler method just keep this line and remove all other.
_imageView.center.y = [recognizer locationInView:[_imageView superView]].y;
You need to get location in superView, not imageView itself. And just change the y value of center.
I have a couple of UIScrollViews in my view controller. I want to overlay a view that captures a 2 finger swipe via UIPanGestureRecognizer which will not record the UIScrollView swipe gestures.
When I put a transparent view over my content with a 2 finger pan gesture, my taps and 1 finger swipes are not detected. I tried overwriting the pointInside: method to return NO
but then it doesn't record my 2 finger swipe.
The effect is similar to the 4 finger swipe to change apps.
You don't need an overlay view.
First implement UIPanGestureRecognizer that will handle 2 finger pan and assign it to your view that contains UIScrollViews
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]
initWithTarget:self
action:#selector(handlePan:)];
panGestureRecognizer.delegate = self;
panGestureRecognizer.minimumNumberOfTouches = 2;
panGestureRecognizer.maximumNumberOfTouches = 2;
[self.view addGestureRecognizer:panGestureRecognizer];
Use UIGestureRecognizerDelegate to handle 2 finger pan with UIScrollView pan gesture
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
And finally you are able to handle 2 fingers pan
- (void)handlePan:(UIPanGestureRecognizer *)gestureRecognizer
{
NSLog(#"pan");
}
If you want to stop scrolling UIScrollView when two finger pan is detected you can disable and enable UIScrollView pan recognizers
- (void)handlePan:(UIPanGestureRecognizer *)gestureRecognizer
{
if(gestureRecognizer.state == UIGestureRecognizerStateBegan)
{
_scrollView.panGestureRecognizer.enabled = NO;
}
if(gestureRecognizer.state == UIGestureRecognizerStateEnded)
{
_scrollView.panGestureRecognizer.enabled = YES;
}
NSLog(#"pan");
}
If you don't really need the overlay you can solve this with just gesture recognizers. I wrote this up as a test:
- (void)viewDidLoad {
[super viewDidLoad];
self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
_scrollView.contentSize = CGSizeMake(self.view.bounds.size.width * 2, self.view.bounds.size.height);
UIView *green = [[UIView alloc] initWithFrame:self.view.bounds];
[green setBackgroundColor:[UIColor greenColor]];
UIView *blue = [[UIView alloc] initWithFrame:CGRectOffset(self.view.bounds, self.view.bounds.size.width, 0)];
[blue setBackgroundColor:[UIColor blueColor]];
[_scrollView addSubview:green];
[_scrollView addSubview:blue];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(twoFingerPan:)];
[pan setMinimumNumberOfTouches:2];
[pan setMaximumNumberOfTouches:2];
[pan setDelaysTouchesBegan:YES];
[_scrollView addGestureRecognizer:pan];
[self.view addSubview:_scrollView];
}
- (void)twoFingerPan:(UIPanGestureRecognizer *)gesture {
switch (gesture.state) {
case UIGestureRecognizerStateBegan:
self.scrollView.scrollEnabled = NO;
break;
case UIGestureRecognizerStateCancelled:
case UIGestureRecognizerStateEnded:
case UIGestureRecognizerStateFailed:
self.scrollView.scrollEnabled = YES;
break;
default:
break;
}
NSLog(#"2 Fingers!");
}
I get the twoFingerPan: call back for when 2 fingers are used. The scroll view's panGestureRecognizer is still working at that point so I disable scrolling on the scroll view to handle the 2 finger pan. I've found this method work's pretty well. One sort of wonky thing is if the scroll view is decelerating the 2 finger gesture recognizer isn't called. Hope that helps!
In my app I should implement the drag and drop of a imageView; the problem is that my imageView is inside a scrollview; it's my code
- (void) viewDidLoad{
[super viewDidLoad];
UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(dragGestureChanged:)];
[scrollViewAlfabeto addGestureRecognizer:downwardGesture];
for (UIGestureRecognizer *gestureRecognizer in myscrollView.gestureRecognizers)
{
[gestureRecognizer requireGestureRecognizerToFail:downwardGesture];
}
}
- (void) dragGestureChanged:(UIPanGestureRecognizer*)gesture
{
CGPoint point = [gesture locationInView:scrollViewAlfabeto];
if (gesture.state == UIGestureRecognizerStateBegan)
{
[imageViewToMove removeFromSuperview];
[self.view addSubview:imageViewToMove];
UIView *draggedView = [myscrollView hitTest:point withEvent:nil];
if ([draggedView isKindOfClass:[UIImageView class]])
{
imageViewToMove = (UIImageView*)draggedView;
}
}
else if (gesture.state == UIGestureRecognizerStateChanged)
{
imageToMove.center = point;
}
else if (gesture.state == UIGestureRecognizerStateEnded ||
gesture.state == UIGestureRecognizerStateCancelled ||
gesture.state == UIGestureRecognizerStateFailed)
{
// Determine if dragged view is in an OK drop zone
// If so, then do the drop action, if not, return it to original location
NSLog(#"point.x final:%f", point.x);
NSLog(#"point.y final:%f", point.y);
if (CGRectContainsPoint(goal.frame, point)){
imageToMove.frame = CGRectMake(167, 159, 100, 100);
}
else{
[imageToMove removeFromSuperview];
[myscrollView addSubview:imageToMove];
[imageToMove setFrame:CGRectMake(12, 38, 100, 100)];
imageToMove = nil;
}
}
}
Then with my code I'm able to take an imageView from scrollView with longpress, drag it inside "self.view"; also if I drop this imageView over another imageView in self.view it puts on it. It work fine. But I have two problems:
1- when I drag this imageView and I do
[imageViewToMove removeFromSuperview];
[self.view addSubview:imageViewToMove];
the image view don't appear under my finger but in other position and I want that it remains under my finger
2- This code work only the first time when I launch my viewcontroller, because If I don't drop the imageview over other imageview inside self.view, itr return inside scrollview, but If I want drag it a second time, it don't work.
Can you help me?
I'm not advanced in objc, but...
Allow user ineraction [self.view userInteractionEnabled:YES];
Try [self.view setMultipleTouchEnabled:YES];
Taken from the documentation of UIView in relation to userInteractionEnabled:
Discussion
When set to NO, user events—such as touch and
keyboard—intended for the view are ignored and removed from the event
queue. When set to YES, events are delivered to the view normally. The
default value of this property is YES.
During an animation, user interactions are temporarily disabled for
all views involved in the animation, regardless of the value in this
property. You can disable this behavior by specifying the
UIViewAnimationOptionAllowUserInteraction option when configuring the
animation.
Hope it works