How to setup a subclass of UIScrollView to respond to touch events? - ios

I recently had a problem regarding not being able to register touches events (touchesMoved, etc) from within a UIScrollView. After talking with lots of people and reading tons of posts, it turns out UIScrollView does't accept touches itself, and instead the touches need to be passed to a UIScrollView subclass.
I am very new to objective-c, and am having a terrible time wrapping my head around how subclasses are defined (in separate .h/.m files or somehow in #interface or something), as well as how iOS deals with responder chains.
Please let me describe my exact situation, and anyone willing to explain what I need to do in noob-speak will be really appreciated.
I have a single page in my app, and I changed it's default UIView to UIScrollView, so if I inspect it in InterfaceBuidler all I see is my SampleViewController and UIScrollView. I linked my UIScrollView to the #Interface of SampleViewControler.h like this:
#import <UIKit/UIKit.h>
#interface SampleViewController : UIViewController
{
}
#property (strong, nonatomic) IBOutlet UIScrollView *mainScroller;
#end
And I referenced my UIScrollView in SampleViewController.m like this:
#import "SampleViewController.h"
#interface SampleViewController ()
#end
#implementation SampleViewController
#synthesize mainScroller = _mainScroller;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(#"Movement!");
}
-(void)viewWillAppear:(BOOL)animated
{
[_mainScroller setContentOffset:CGPointMake(0,0) animated:YES];
}
If I change the class of UIScrollView to UIView, the touches are detected and I fire off a few NSLog messages. However, once UIView is set back to UIScrollView, touches are ignored.
From what I understand I need to setup a subclass of UIScrollView with the code:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(#"Movement!");
}
...and then change my SampleViewController.m to have the code:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self.nextResponder nextResponder] touchesMoved:touches withEvent:event];
}
However, I really don't understand 1) how to setup such a subclass, and 2) why this would work, since I don't see why [[self.nextResponder nextResponder] touchesMoved:touches withEvent:event]; would ever be called in the first place from within SampleViewController.m, since my similar NSLog(#"Movement!"); statement is never executed.
I have tried every tutorial I could find, and am turning toward to the expertise of SE! Thanks.

You're thinking about this wrong. If you want to know when a scrollView is moving, there's no need to subclass it. iOS has set up all the methods you need inside of the UIScrollViewDelegate. IF however you want to say, pick up touchEvents for items based inside the scrollView, then that is perfectly okay. You need to then just subclass the items inside the scrollView and pick up the touchEvents inside the respective classes though. But for just standard scrollView methods you should set it up as so:
.H
#import <UIKit/UIKit.h>
#interface SampleViewController : UIViewController<UIScrollViewDelegate>
{
}
#property (strong, nonatomic) IBOutlet UIScrollView *mainScroller;
#end
.M
#import "SampleViewController.h"
#interface SampleViewController ()
#end
#implementation SampleViewController
#synthesize mainScroller = _mainScroller;
-(void)viewDidLoad
{
self.mainScroller.delegate=self;//Adopt the delegate for the scrollView..this is the important line
}
Then just implement the UIScrollViewDelegateMethods to grab movement etc. Undefined behavior will occur when trying to pick up touchEvents inside a scrollView/tableView, since the scrollView itself already implements those touchEvents behind the scenes
Look at all the methods on the Developer site and implement them in your .M file. Since you've adopted the delegate in viewDidLoad, these will be your scrollView call backs. I've listed a few of them before but go ahead and look on the UIScrollViewDelegate Protocol site
– scrollViewDidScroll:
– scrollViewWillBeginDragging:
– scrollViewWillEndDragging:withVelocity:targetContentOffset:
– scrollViewDidEndDragging:willDecelerate:
– scrollViewShouldScrollToTop:
– scrollViewDidScrollToTop:
– scrollViewWillBeginDecelerating:
– scrollViewDidEndDecelerating:

I posted an answer to a similar question a few days ago that might help you as well. See this question and my answer.
It looks like you're close to getting it working, but you've gotten a bit confused about where to put the touchesMoved methods.
In your subclass of UIScrollView, you should have:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self.nextResponder nextResponder] touchesMoved:touches withEvent:event];
}
And in your SampleViewController.m file:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(#"Movement!");
}
(You have these two around the other way in your question.)

Related

Connecting a UIScrollView to a UIView class

I'm currently creating a "slide-show" of pictures that the user can scroll through. Following a guide, I made it so that the UIScrollView I am using shows the edges of the previous and next pictures as the user scrolls along. This comes with a side-effect of the user not being able to scroll if he touches on one of the edges of the pictures, because these edges are technically not within the border of the UIScrollView itself. In order to compensate for this, I am going to create a UIView in which I will embed the UIScrollView. The UIVew will be extend the entire width of the page so that the user can scroll when touching the edges of the pictures. To do this, I need to connect the UIScrollView to the code of the UIView through an IBOutlet. Usually this is simply accomplished by Ctrl-clicking on the UIScrollView and dragging to the code. However, this does not seem to work for me and I am stumped as to why.
Here is a screenshot of the environment I am dealing with when I try to ctrl-click on the UIScrollView and drag to the code to create an IBOutlet (it simply doesn't give the option to create anything).
Here is a screenshot of what running the simulator produces. If i try to click and drag where my mouse currently is, it doesn't scroll, which is the problem I am trying to correct.
It is because you should link your storyboard view to UIView class. You can choose your ScrollViewController class in custom class settings. I added the sample jpg
what you are looking for is not that 'easy' by just connecting the two.
There are two options:
1) In the future you should use a UICollectionView and implement the paging behaviour yourself, that is the cleanest code I think.
NEVER MIND THE SECOND OPTION - I DIDN'T SEE YOU ACTUALLY ALREADY USED THIS
2) To directly answer your question:
You have to subclass the UIView that contains the UIScrollView like this:
header:
#import <UIKit/UIKit.h>
#interface SCTouchForwardView : UIView
#property (nonatomic, weak) IBOutlet UIView* receiver;
#property (nonatomic, assign) BOOL force;
#end
Implementation:
#import "SCTouchForwardView.h"
#implementation SCTouchForwardView
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView* result = [super hitTest:point withEvent:event];
if (![result isKindOfClass:[SCTouchForwardView class]]) {
return result;
}
if (result==self) {
UIView *result = [self.receiver hitTest:[self convertPoint:point toView:self.receiver] withEvent:event];
if (result) {
return result;
}else{
if (self.force) {
return self.receiver;
}
return nil;
}
}
return nil;
}
#end
When you want to use this, you just have to Right-Click-Drag from the container to the UIScrollview and select 'receiver' and what you tried to do will work!

How to get a UIView object to communicate with a ViewController object

I'm working on an iPhone app in StoryBoard. It has a UIScrollView in it. Inside of this, it has a SliderView, which is a custom subclass that I wrote that derives from UIView.
Inside SliderView I'm executing this method:
// Inside SliderView.m
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// whenever someone touches inside of SliderView, this method fires
}
Here's my problem. In my StoryBoard, I would like to disable the bouncy vertical scrolling of the UIScrollView.
Normally, that would be easy. Assuming I had connected the UIScrollView as an IBOutlet in the app's main ViewController, I could paste this into that file:
// Inside ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.scrollView.bounces = NO;
}
Unfortunately, this isn't so easy because I want this disabling to occur only when touchesBegan is fired.
So here's where I'm completely stumped: how can I get the SliderView.m file to communicate with the ViewController.m file?
Use delegate for this:
SliderView.h
// SliderView.h
#protocol SliderViewDelegate <NSObject>
#optional
- (void) isScrollViewToBounce:(BOOL)isBounce;
#end
#interface SliderView : UIView
#property (nonatomic, weak) id <SliderViewDelegate> sliderViewDelegate;
#end
SliderView.m
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.sliderViewDelegate isScrollViewToBounce:NO];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self.sliderViewDelegate isScrollViewToBounce:YES];
}
ViewController.m
#import "SliderView.h"
#interface ViewController () <SliderViewDelegate>
#end
viewDidLoad() method
- (void)viewDidLoad {
[super viewDidLoad];
self.sliderView setSlideViewDelegate:self];
}
Create Delegate method in your ViewController:
- (void) isScrollViewToBounce:(BOOL)isBounce {
self.scrollView.bounces = isBounce;
}
Also do not forget to remove delegation
#pragma mark Memory management methods
//---------------------------------------------------------------
- (void)dealloc {
// Release resources here.
[self.scrollView setSliderViewDelegate:nil]
}

Hiding buttons in a UIViewController from a UIView delegate

I have a UIView class that is loaded in to a UIViewController as a subview, to capture touches and draw them to the screen (a simple drawing app). I want to hide some buttons in the UIViewController when drawing begins. In the UIViewController (DrawingController.m) viewDidLoad method:
//init the draw screen
drawScreen=[[MyLineDrawingView alloc]initWithFrame:self.view.bounds];
[drawScreen setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:drawScreen];
I have a method in the UIViewController (DrawingController.m) that is hiding my colour picker, brush size buttons etc that are present within the UIViewController. The hide method works fine when called from the same class (DrawingController.m). Basically when the -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event method is called within the UIView class (MyLineDrawingView.m) I am hoping to hide the buttons:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
DrawingController *drawController = [[DrawingController alloc] init];
[drawController hideDrawIcons];
}
I've added some logging to the hideDrawIcons method within the UIViewController and it is getting called, but all of my hiding code is not working:
self.undoBtn.hidden = YES;
I suspect this is because I am making a new instance of the UIViewController class with DrawingController *drawController = [[DrawingController alloc] init]; - but I'm not sure how to do things differently?
I have of course exposed the correct method in the DrawingController.h header file, to be able to call it from the UIView class (MyLineDrawingView.m):
-(void)hideDrawIcons;
Hopefully all of that makes sense, thanks in advance!
You are right. You do not need to make create new instance of DrawingController.
All you need yo have pointer of your DrawingController in your View class. If you want to know more about this technology you can read about Delegate pattern. If not, here is simple steps.
Add protocol in your MyLineDrawingView.h file ( or you can create separated file for it )
#protocol MyLineDrawingProtocol <NSObject>
-(void)hideDrawIcons;
#end
In your DrawingController.h
#interface DrawingController <MyLineDrawingProtocol>
{
// members ....
}
#end
In your MyLineDrawingView.h
#interface MyLineDrawingView
{
// members ....
}
#property (nonatomic,weak) id <MyLineDrawingProtocol> delegate;
#end
Set delegate for your view
//init the draw screen
drawScreen=[[MyLineDrawingView alloc]initWithFrame:self.view.bounds];
drawScreen.delegate = self;// self is a pointer of DrawingController
[drawScreen setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:drawScreen];
And last change. Call hideDrawIcons method for delegate ( DrawingController )
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if ( [self.delegate respondsToSelector:#selector(hideDrawIcons)] )
[self.delegate hideDrawIcons];
}
Yes, you're creating a new copy of the view controller in your view, which is wrong. What you want is to have a reference to the actual view controller. Here's how you can do it:
In MyLineDrawingView, declare a property:
#property (nonatomic, weak) DrawingController *drawingController;
Note that it is declared as weak, which prevents a retain cycle.
When instantiating the view:
drawScreen=[[MyLineDrawingView alloc]initWithFrame:self.view.bounds];
drawScreen.drawingController = self; // pass the actual view controller instance to the drawScreen object.
Finally, in MyLineDrawingView:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.drawingController hideDrawIcons];
}

touchesBegan not invoked for TextView

I am unable to call touchesBegan from a text view.
Its working fine for me in a dummy project where i have just a View and inside it a TextView.
When I try to do it in real proj , having hierarchy like: (i feel here is some problem)
view (parent)
scrollview(subview)
view (grandSubview
textview.
the delegate is not getting called.
.h file
#interface ActionViewController : UIViewController<UITextViewDelegate>
#property (weak, nonatomic) IBOutlet UITextView *actionTakenTextView;
.m file
- (void)viewDidLoad
{
[super viewDidLoad];
actionTakenTextView.delegate=self; //actiontakentextview is the text view i am using.
actionTakenTextView.layer.borderWidth=1;
actionTakenTextView.layer.borderColor=[[UIColor grayColor] CGColor];
// Below property is to set rounded corner of text view.
actionTakenTextView.layer.cornerRadius=5.0;
actionTakenTextView.clipsToBounds=YES;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(#"touchesBegan:withEvent:");
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
}
I feel i am missing something very small here..please help.
thanks in adv.

Handling touches within UIScrollview

I have a view that contains a UIScrollView. The UIScrollView contains an UIImageView (only one for now but there will be more latter). I want to be able to drag the UIImageView out of the UIScrollView and into the superview.
I have reviewed every similar question and example I can find online and still cant get my head around how this works.
At first I couldn't get touches to register all whithin the scrollview. After a lot of searching I have found a way to get touchesbegan to register as follows:
First I created a new view based project and in the auto-created "ViewController.h"
I created an IBOutlet named slider.
Then in the auto-created "ViewController.m" I created the UIScrollview.
In IB I added a UIScrollView to the storyboard then connected it to the "slider" IBOutlet.
Next I added class file to the projects. This new class is a subclass os UIImageView. I named this class "DragableImage" In the
Then in IB I dropped an image into the UIScrollview clicked on it and changed the class to "DragableImage"
In the DragableImage.m I voided touches began and simply told it to become hidden if clicked.
This works and the touch registers and makes the image disappear but how do I now add the new image to the main view and have it follow my finger?
This is what I have in the way of code:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController {
IBOutlet UIScrollView *slider;
}
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[slider setScrollEnabled:YES];
[slider setContentSize:CGSizeMake(306, 1560)];
[slider setShowsVerticalScrollIndicator:NO];
slider.canCancelContentTouches = NO;
slider.delaysContentTouches = NO;
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#end
DragableImage.h
#import <UIKit/UIKit.h>
#interface DragableImage : UIImageView
#end
DragableImage.m
#implementation DragableImage
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
self.hidden = YES;
}
#end
How to make this work?
There is one obvious problem that can arise here. Namely, how to tell the difference between dragging to scroll and dragging an image. The way I would handle this is to setup a tap and hold gesture recognizer (http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/GestureRecognizers/GestureRecognizers.html).
Once you detect a hold you could set it up so that further touches/gestures get routed to you drag and drop code. You can find a nice tutorial for that here:
http://www.ancientprogramming.com/2012/04/05/drag-and-drop-between-multiple-uiviews-in-ios/

Resources