Mutually Exclusive Toggle Behavior for Segments in UISegmentedContol - iphone

Is it possible to deselect a segment of the UISegmentedControl by tapping it the second time? I am currently using a UILongPressGestureRecognizer object to setSelectedSegmentIndex to UISegmentedControlNoSegment. However, I'd rather have the selected segment deselect on the second tap.

Another method is to subclass the UISegmentedControl. For example:
#interface ToggleSegmentedControl : UISegmentedControl
{
NSUInteger selectedSegment;
}
#end
#implementation ToggleSegmentedControl
-(id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
selectedSegment = self.selectedSegmentIndex;
}
return self;
}
-(void)awakeFromNib
{
selectedSegment = self.selectedSegmentIndex;
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if( selectedSegment == self.selectedSegmentIndex && selectedSegment!=-1)
{
self.selectedSegmentIndex= UISegmentedControlNoSegment;
selectedSegment=-1;
}
else
{
selectedSegment=self.selectedSegmentIndex;
}
}
#end
The above code may require further tweaking to suit individual specifications.

Related

How to handle events (Touch Up Inside/Outside) for UItableViewCell with a text field?

I have a custom UITableViewCell which has a text field inside it. I have created it using IB and have a custom class with it.
Now, my issue is that I want to setup the text field so that during text entry if the user clicks outside the text field (without hitting the return/done key on the keypad), the field resigns first responder. I understand, that do that I need to handle the Touch Up Inside Event. However my tableview class never receives this event even though I have done the connections. I am assuming that its because its not subclass of UIcontrol, which I cant make it as it needs to be UITableViewCel.
So whats the solution?? How do I receive these events??
Header File:
#import <UIKit/UIKit.h>
#interface MMSingleTextFieldCell : UITableViewCell <UITextFieldDelegate>
// Properties
#property (weak, nonatomic) IBOutlet UITextField *singleTextField;
// Methods
- (IBAction)eventTouchUpOutside:(id)sender;
- (IBAction)eventTouchUpInside:(id)sender;
#end
Class File:
#import "MMSingleTextFieldCell.h"
#implementation MMSingleTextFieldCell
#synthesize singleTextField;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (IBAction)eventTouchUpOutside:(id)sender {
[singleTextField resignFirstResponder];
}
- (IBAction)eventTouchUpInside:(id)sender {
[singleTextField resignFirstResponder];
}
I have just recently open sourced a project on Github that should make this all relatively easy to do. It includes a class that can be easily inserted into a cell and a sample project demonstrating its capabilities.
If you look in RootTableViewController's viewDidLoadMethod you will see that I am adding a gesture recognizer:
self.tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(dismissKeyboard)];
_tapGestureRecognizer.delegate = self;
_tapGestureRecognizer.cancelsTouchesInView = NO;
[self.tableView addGestureRecognizer:_tapGestureRecognizer];
Add the dismiss keyboard method:
- (void)dismissKeyboard {
[_textField resignFirstResponder];
}
Add a gesture recognizer callback (in RootTableViewController):
//see: http://stackoverflow.com/questions/7195661/why-is-uigesturerecognizer-being-called-on-my-textfield-clear-button
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if([touch.view isKindOfClass:[UITextField class]] ||
[touch.view isKindOfClass:[UIButton class]])
{
return NO;
}
return YES;
}
Of course, this means you have to make RootTableViewController adhere to the UIGestureRecognizerDelegate protocol (in the header file):
#interface RootTableViewController : UITableViewController<SATextFieldDelegate, UIGestureRecognizerDelegate>
If you want the user to scroll the table view and dismiss the keyboard implement the following table view delegate callback:
- (void)scrollViewWillBeginDragging:(UIScrollView *)activeScrollView {
if (_textField.isFirstResponder) {
[self dismissKeyboard];
}
}
I believe this is the function you want.
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
if (_textField.isFirstResponder) {
[self dismissKeyboard];
}
}
Try this:
1) Implement the UIGestureRecognizerDelegate protocol
2) In viewDidLoad for example, create the following
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(hideKeyboard:)];
tap.delegate = self;
[self.view addGestureRecognizer:tap];
3) Now, implement the method from protocol from 1
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
// Use this for allow some control to receive his natural tap event. You can use tap.cancelsTouchesInView = NO; in the 2 step instead of this, try both of then and choose on your own.
if (touch.view == <some control>) {
//NSLog(#"NO");
return NO;
}
//NSLog(#"YES");
return YES;
}
4) finally, implement the callback for tap
-(void) hideKeyboard:(id)sender{
if (<your edit text>.isEditing) {
[<your edit text> resignFirstResponder];
}
}
I hope this will help, or at least point you to the right direction

UIScrollView inside UITableViewCell touch detect

I have a tableview with 8 custom cells. in the 8th cell I added a scrollView with paging enabled so I can show page 1 and page 2 (or 3, 4... 10) without have a very high cell.
The problem is with the scrollView I can't use didSelectRowAtIndexPath because the cell is behind the scrollView so I'm trying to detect scrollView tap (not swipe).
I played with touchesBegan and touchesEnded but they are never called (I know touches work with UIView only, but maybe.....)
Any help is very appreciated.
Thanks,
Max
There is a trick Apple recommends to use in this case, in theirs WWDC 2014 session "Advanced scrollviews" (See Demo starting from 8:10):
[cell.contentView addSubview:_scrollView];
[_scrollView setUserInteractionEnabled:NO];
[cell.contentView addGestureRecognizer:_scrollView.panGestureRecognizer];
That's all what needs to be done, no need to override touchesBegan:, touchesMoved: and others.
I used solution based on overriding of touchesBegan:, touchesMoved:, touchesEnded: and touchesCancelled: previously, but sometimes it caused a weird behaviour: when select a certain cell, method -tableView:didSelectRowAtIndexPath: was called for cell with different indexPath.
Solution from Apple has no side effects so far and looks more elegant.
There is also an elegant resolution:
Create a SubClass from UIScrollView and override the following methods
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self superview]touchesBegan:touches withEvent:event];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self superview]touchesMoved:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self superview]touchesCancelled:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self superview]touchesEnded:touches withEvent:event];
}
Passing every touch to the superview of the scroll view and then the didSelectRowAtIndexPath will be called.
Solved subclassing both uitableviewcell and uiscrollview.
It worked for my needs. Hope it can help.
Max
myScrollView.h
#import <UIKit/UIKit.h>
#interface myScrollView : UIScrollView {
}
#end
myScrollView.m
#import "myScrollView.h"
#implementation myScrollView
- (id)initWithFrame:(CGRect)frame {
return [super initWithFrame:frame];
}
- (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event
{
NSLog(#"touch scroll");
// If not dragging, send event to next responder
if (!self.dragging)
[self.nextResponder touchesEnded: touches withEvent:event];
else
[super touchesEnded: touches withEvent: event];
}
myCell.h
#import <UIKit/UIKit.h>
#interface myCell : UITableViewCell {
}
#end
myCell.m
#import "myCell.h"
#implementation myCell
- (id)initWithFrame:(CGRect)frame {
return [super initWithFrame:frame];
}
- (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event
{
NSLog(#"touch cell");
// If not dragging, send event to next responder
[super touchesEnded: touches withEvent: event];
}
RootViewController.h
#import <UIKit/UIKit.h>
#class myCell;
#class myScrollView;
#interface RootViewController : UITableViewController {
myCell *cell;
myScrollView *scrollView;
}
#end
RootViewController.m
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 3;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
// my custom cell
cell = [[myCell alloc] init];
if (cell == nil) {
cell = [[[myCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// the custom scroll view
scrollView = [[myScrollView alloc] initWithFrame:cell.frame];
scrollView.contentSize = CGSizeMake(640, 40);
[cell.contentView addSubview:scrollView];
//something to add in scrollView
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 20)];
label.text = #"some text";
[scrollView addSubview:label];
// Configure the cell.
return cell;
}
The selected answer is correct, but I updated the code based on a bug I was getting.
In the subclassed scroll view add the following code.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if (self.dragging) {
[super touchesMoved:touches withEvent:event];
} else {
if ([self.delegate isKindOfClass:[UITableViewCell class]]) {
[(UITableViewCell *)self.delegate touchesCancelled:touches withEvent:event];
}
[self.superview touchesMoved:touches withEvent:event];
}
}
If your self.delegate is not the UITableViewCell, than replace that property with a property to your cell.
The cell needs to retrieve the cancel touch event during movement to prevent the undesired results. It can be easily reproducible as follows.
Highlight the cell (assuming the scroll view is over the whole cell, if not highlight the scroll view)
While the cell is highlighted, drag the table view
Select any other cell and now the previously highlighted cell will retrieve the didSelectCell state
Another point to mention is that order matters! If the self.delegate is not called before the self.superview then the highlighted state wont happen.
I found the simplest solution for my needs:
subclass UIScrollView touchesEnded method and post a notification.
In the UITableview add an observer in viewdidAppear (remove it in viewdiddisappear) to call a function that call tableview didSelectRowForIndexPath.
Something like this (swift version)
// myScrollView.swift
import UIKit
class myScrollView: UIScrollView {
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
NSNotificationCenter.defaultCenter().postNotificationName("selectTVRow", object: nil)
}
}
In your tableView:
// ItemsList.swift
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectFourthRow", name: "selectTVRow", object: nil)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "selectfourthrow", object: nil)
}
func selectFourthRow() {
let rowToSelect:NSIndexPath = NSIndexPath(forRow: 4, inSection: 0);
self.tableView(self.tableView, didSelectRowAtIndexPath: rowToSelect);
}
/*
.... rest of your tableview Datasource and Delegate methods...
numberOfSectionsInTableView, numberOfRowsInSection, cellForRowAtIndexPath
*/

How can I loop through all subviews of a UIView, and their subviews and their subviews

How can I loop through all subviews of a UIView, and their subviews and their subviews?
Use recursion:
// UIView+HierarchyLogging.h
#interface UIView (ViewHierarchyLogging)
- (void)logViewHierarchy;
#end
// UIView+HierarchyLogging.m
#implementation UIView (ViewHierarchyLogging)
- (void)logViewHierarchy
{
NSLog(#"%#", self);
for (UIView *subview in self.subviews)
{
[subview logViewHierarchy];
}
}
#end
// In your implementation
[myView logViewHierarchy];
Well here is my solution using recursion and a wrapper(category/extension) for the UIView class.
// UIView+viewRecursion.h
#interface UIView (viewRecursion)
- (NSMutableArray*) allSubViews;
#end
// UIView+viewRecursion.m
#implementation UIView (viewRecursion)
- (NSMutableArray*)allSubViews
{
NSMutableArray *arr=[[[NSMutableArray alloc] init] autorelease];
[arr addObject:self];
for (UIView *subview in self.subviews)
{
[arr addObjectsFromArray:(NSArray*)[subview allSubViews]];
}
return arr;
}
#end
Usage : Now you should be looping through all the sub views and manipulate them as needed.
//disable all text fields
for(UIView *v in [self.view allSubViews])
{
if([v isKindOfClass:[UITextField class]])
{
((UITextField*)v).enabled=NO;
}
}
Here's another Swift implementation:
extension UIView {
var allSubviews: [UIView] {
return self.subviews.flatMap { [$0] + $0.allSubviews }
}
}
A solution in Swift 3 that gives all subviews without including the view itself:
extension UIView {
var allSubViews : [UIView] {
var array = [self.subviews].flatMap {$0}
array.forEach { array.append(contentsOf: $0.allSubViews) }
return array
}
}
I tag everything when it's created. Then it's easy to find any subview.
view = [aView viewWithTag:tag];
Just found an interesting way to do this through the debugger:
http://idevrecipes.com/2011/02/10/exploring-iphone-view-hierarchies/
references this Apple Technote:
https://developer.apple.com/library/content/technotes/tn2239/_index.html#SECUIKIT
Just make sure your debugger is paused (either set a break point of pause it manually) and you can ask for the recursiveDescription.
Here is an example with actual view looping and breaking functionality.
Swift:
extension UIView {
func loopViewHierarchy(block: (_ view: UIView, _ stop: inout Bool) -> ()) {
var stop = false
block(self, &stop)
if !stop {
self.subviews.forEach { $0.loopViewHierarchy(block: block) }
}
}
}
Call example:
mainView.loopViewHierarchy { (view, stop) in
if view is UIButton {
/// use the view
stop = true
}
}
Reversed looping:
extension UIView {
func loopViewHierarchyReversed(block: (_ view: UIView, _ stop: inout Bool) -> ()) {
for i in stride(from: self.highestViewLevel(view: self), through: 1, by: -1) {
let stop = self.loopView(view: self, level: i, block: block)
if stop {
break
}
}
}
private func loopView(view: UIView, level: Int, block: (_ view: UIView, _ stop: inout Bool) -> ()) -> Bool {
if level == 1 {
var stop = false
block(view, &stop)
return stop
} else if level > 1 {
for subview in view.subviews.reversed() {
let stop = self.loopView(view: subview, level: level - 1, block: block)
if stop {
return stop
}
}
}
return false
}
private func highestViewLevel(view: UIView) -> Int {
var highestLevelForView = 0
for subview in view.subviews.reversed() {
let highestLevelForSubview = self.highestViewLevel(view: subview)
highestLevelForView = max(highestLevelForView, highestLevelForSubview)
}
return highestLevelForView + 1
}
}
Call example:
mainView.loopViewHierarchyReversed { (view, stop) in
if view is UIButton {
/// use the view
stop = true
}
}
Objective-C:
typedef void(^ViewBlock)(UIView* view, BOOL* stop);
#interface UIView (ViewExtensions)
-(void) loopViewHierarchy:(ViewBlock) block;
#end
#implementation UIView (ViewExtensions)
-(void) loopViewHierarchy:(ViewBlock) block {
BOOL stop = NO;
if (block) {
block(self, &stop);
}
if (!stop) {
for (UIView* subview in self.subviews) {
[subview loopViewHierarchy:block];
}
}
}
#end
Call example:
[mainView loopViewHierarchy:^(UIView* view, BOOL* stop) {
if ([view isKindOfClass:[UIButton class]]) {
/// use the view
*stop = YES;
}
}];
With the help of Ole Begemann. I added a few lines to incorporate the block concept into it.
UIView+HierarchyLogging.h
typedef void (^ViewActionBlock_t)(UIView *);
#interface UIView (UIView_HierarchyLogging)
- (void)logViewHierarchy: (ViewActionBlock_t)viewAction;
#end
UIView+HierarchyLogging.m
#implementation UIView (UIView_HierarchyLogging)
- (void)logViewHierarchy: (ViewActionBlock_t)viewAction {
//view action block - freedom to the caller
viewAction(self);
for (UIView *subview in self.subviews) {
[subview logViewHierarchy:viewAction];
}
}
#end
Using the HierarchyLogging category in your ViewController. You are now have freedom to what you need to do.
void (^ViewActionBlock)(UIView *) = ^(UIView *view) {
if ([view isKindOfClass:[UIButton class]]) {
NSLog(#"%#", view);
}
};
[self.view logViewHierarchy: ViewActionBlock];
Need not create any new function. Just do it when debugging with Xcode.
Set a breakpoint in a view controller, and make the app pause at this breakpoint.
Right click the empty area and press "Add Expression..." in Xcode's Watch window.
Input this line:
(NSString*)[self->_view recursiveDescription]
If the value is too long, right click it and choose "Print Description of ...". You will see all subviews of self.view in the console window. Change self->_view to something else if you don't want to see subviews of self.view.
Done! No gdb!
Here is a recursive code:-
for (UIView *subViews in yourView.subviews) {
[self removSubviews:subViews];
}
-(void)removSubviews:(UIView *)subView
{
if (subView.subviews.count>0) {
for (UIView *subViews in subView.subviews) {
[self removSubviews:subViews];
}
}
else
{
NSLog(#"%i",subView.subviews.count);
[subView removeFromSuperview];
}
}
By the way, I made an open source project to help with this sort of task. It's really easy, and uses Objective-C 2.0 blocks to execute code on all views in a hierarchy.
https://github.com/egold/UIViewRecursion
Example:
-(void)makeAllSubviewsGreen
{
[self.view runBlockOnAllSubviews:^(UIView *view) {
view.backgroundColor = [UIColor greenColor];
}];
}
Here is a variation on Ole Begemann's answer above, which adds indentation to illustrate the hierarchy:
// UIView+HierarchyLogging.h
#interface UIView (ViewHierarchyLogging)
- (void)logViewHierarchy:(NSString *)whiteSpaces;
#end
// UIView+HierarchyLogging.m
#implementation UIView (ViewHierarchyLogging)
- (void)logViewHierarchy:(NSString *)whiteSpaces {
if (whiteSpaces == nil) {
whiteSpaces = [NSString string];
}
NSLog(#"%#%#", whiteSpaces, self);
NSString *adjustedWhiteSpaces = [whiteSpaces stringByAppendingFormat:#" "];
for (UIView *subview in self.subviews) {
[subview logViewHierarchy:adjustedWhiteSpaces];
}
}
#end
The code posted in this answer traverses all windows and all views and all of their subviews. It was used to dump a printout of the view hierarchy to NSLog but you can use it as a basis for any traversal of the view hierarchy. It uses a recursive C function to traverse the view tree.
I wrote a category some time back to debug some views.
IIRC, the posted code is the one that worked. If not, it will point you in the right direction. Use at own risk, etc.
This displays the hierarchy level as well
#implementation UIView (ViewHierarchyLogging)
- (void)logViewHierarchy:(int)level
{
NSLog(#"%d - %#", level, self);
for (UIView *subview in self.subviews)
{
[subview logViewHierarchy:(level+1)];
}
}
#end
Wish I'd found this page first, but if (for some reason) you want to do this non-recursively, not in a Category, and with more lines of code
I think all of the answers using recursion (except for the debugger option) used categories. If you don't need/want a category, you can just use a instance method. For instance, if you need to get an array of all labels in your view hierarchy, you could do this.
#interface MyViewController ()
#property (nonatomic, retain) NSMutableArray* labelsArray;
#end
#implementation MyViewController
- (void)recursiveFindLabelsInView:(UIView*)inView
{
for (UIView *view in inView.subviews)
{
if([view isKindOfClass:[UILabel class]])
[self.labelsArray addObject: view];
else
[self recursiveFindLabelsInView:view];
}
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.labelsArray = [[NSMutableArray alloc] init];
[self recursiveFindLabelsInView:self.view];
for (UILabel *lbl in self.labelsArray)
{
//Do something with labels
}
}
The method below creates one or more mutable arrays, then loops through the subviews of the input view. In doing so it adds the initial subview then queries as to whether there are any subviews of that subview. If true, it calls itself again. It does so until the all the views of the hierarchy have been added.
-(NSArray *)allSubs:(UIView *)view {
NSMutableArray * ma = [NSMutableArray new];
for (UIView * sub in view.subviews){
[ma addObject:sub];
if (sub.subviews){
[ma addObjectsFromArray:[self allSubs:sub]];
}
}
return ma;
}
Call using:
NSArray * subviews = [self allSubs:someView];

How to pass touch from a UITextView to a UITableViewCell

I have a UITextView in a custom UITableViewCell. The textview works properly (scrolls, shows text, etc.) but I need the users to be able to tap the table cell and go to another screen. Right now, if you tap the edges of the table cell (i.e. outside the UItextView) the next view is properly called. But clearly inside the uitextview the touches are being captured and not forwarded to the table cell.
I found a post that talked about subclassing UITextView to forward the touches. I tried that without luck. The implementation is below. I'm wondering if maybe a) the super of my textview isn't the uitableviewcell and thus I need to pass the touch some other way or b) If the super is the uitableviewcell if I need to pass something else? Any help would be much appreciated.
#import "ScrollableTextView.h"
#implementation ScrollableTextView
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (parentScrollView) {
[parentScrollView touchesBegan:touches withEvent:event];
}
[super touchesBegan:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
if (parentScrollView) {
[parentScrollView touchesCancelled:touches withEvent:event];
}
[super touchesCancelled:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (parentScrollView) {
[parentScrollView touchesEnded:touches withEvent:event];
}
[super touchesEnded:touches withEvent:event];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if (parentScrollView) {
[parentScrollView touchesMoved:touches withEvent:event];
}
[super touchesMoved:touches withEvent:event];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
#end
Try [theTextView setUserInteractionEnabled:NO]; If the user needs to be able to edit the contents of the TextView, then you might have a design problem here.
Swift 3 : theTextView.isUserInteractionEnabled = false
Storyboard : tick the "User Interaction Enabled" checkbox.
I know that this question has been asked 5 years ago, but the behaviour is still very much needed for some app to have a clickable Cell with UIDataDetectors.
So here's the UITextView subclass I made up to fit this particular behaviour in a UITableView
-(id) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.delegate = self;
}
return self;
}
- (BOOL)canBecomeFirstResponder {
return NO;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UIView *obj = self;
do {
obj = obj.superview;
} while (![obj isKindOfClass:[UITableViewCell class]]);
UITableViewCell *cell = (UITableViewCell*)obj;
do {
obj = obj.superview;
} while (![obj isKindOfClass:[UITableView class]]);
UITableView *tableView = (UITableView*)obj;
NSIndexPath *indePath = [tableView indexPathForCell:cell];
[[tableView delegate] tableView:tableView didSelectRowAtIndexPath:indePath];
}
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
return YES;
}
You can modify this to fit your needs...
Hope it helps someone.
The problem with your solution is that if you put UITextView inside UITableViewCell, its superview won't be the actual cell. There's even a slight difference between iOS 7 and iOS 8 on the cell's view structure. What you need to do is drill down (or drill up) through the hierarchy to get UITableViewCell instance.
I am using and modifying #TheSquad's while loop to get the UITableViewCell, and assign it to a property. Then override those touch methods, use the cell's touches method whenever needed, and just use super's touch method's implementations to get the default behaviour.
// set the cell as property
#property (nonatomic, assign) UITableViewCell *superCell;
- (UITableViewCell *)superCell {
if (!_superCell) {
UIView *object = self;
do {
object = object.superview;
} while (![object isKindOfClass:[UITableViewCell class]] && (object != nil));
if (object) {
_superCell = (UITableViewCell *)object;
}
}
return _superCell;
}
#pragma mark - Touch overrides
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (self.superCell) {
[self.superCell touchesBegan:touches withEvent:event];
} else {
[super touchesBegan:touches withEvent:event];
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if (self.superCell) {
[self.superCell touchesMoved:touches withEvent:event];
} else {
[super touchesMoved:touches withEvent:event];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (self.superCell) {
[self.superCell touchesEnded:touches withEvent:event];
} else {
[super touchesEnded:touches withEvent:event];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
if (self.superCell) {
[self.superCell touchesEnded:touches withEvent:event];
} else {
[super touchesCancelled:touches withEvent:event];
}
}
The answers above don't solve the problem if you have links in the UITextView and want them to work as usual when user taps a link, and pass the tap to the cell if user taps regular text. With the proposed method cell will be "selected" in both cases.
Here are some possible solutions:
https://stackoverflow.com/a/59010352/11448489 - add a tap gesture recognizer to the cell, and set it to require UITextInteractionNameLinkTap recognizer failure. The problem is that UITextInteractionNameLinkTap string is from internal Apple API and can change. Also, we still have to directly call delegate's didSelectRowAtIndexPath, so the cell won't be animated.
Implement override of touchesEnded in the text view. In it perform some selector after delay of at least 0.4s. In the text view delegate cancel this perform request if an interaction with url happened:
class TappableTextView: UITextView, UITextViewDelegate {
var tapHandler: (() -> Void)?
override var delegate: UITextViewDelegate? {
get { self }
set { }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.perform(#selector(onTap), with: nil, afterDelay: 0.5)
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
Self.cancelPreviousPerformRequests(withTarget: self, selector: #selector(onTap), object: nil)
return true
}
#objc func onTap() {
self.tapHandler?()
}
}
It works, but delay is noticeable and annoying. It is not possible to reduce this delay because shouldInteractWith happens after 350ms after touchesEnded.
And we still have to call didSelectRowAtIndexPath.
I came to another solution, which seems to work perfectly if you need clickable links, but no other interactions (not scrollable, selectable etc). Essentially, we need to make the text view ignore all touches which are not in the links area:
class TapPassingTextView: UITextView, UITextViewDelegate {
var clickableRects = [CGRect]()
override func layoutSubviews() {
super.layoutSubviews()
self.updateClickableRects()
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
clickableRects.contains { $0.contains(point) } ? super.hitTest(point, with: event) : nil
}
private func updateClickableRects() {
self.clickableRects = []
let range = NSRange(location: 0, length: self.attributedText.string.count)
self.attributedText.enumerateAttribute(.link, in: range) { link, range, _ in
guard link != nil else { return }
self.layoutManager.enumerateLineFragments(forGlyphRange: range) { rect, _, _, _, _ in
self.clickableRects.append(rect)
}
}
}
}
That's it! Taps on links are working and taps in other areas go below the text view, cells are selected natively.

Detecting taps inside a UIWebView

I have a UIWebView with a navigation bar and toolbar that I want to auto hide. I'm doing that already, but I want to show them when the user taps on the UIWebView.
My problem is that the UIWebView captures all the touches events, and I cannot intercept the one I need.
Is there any workaround for this?
Taken from a blog entry (doesn't load, but thankfully it's Google Cache'd) by Mithin Kumar.
(Mithin, I hope you don't mind me reposting it here; if you do, please let me know in the comments and I will remove it.)
Recently, I was working on a project which required detection of tap and events on the UIWebView. We wanted to find out the HTML element on which the user taps in the UIWebView and then depending on the element tapped some action was to be performed. After some Googling, I found out the most of the users lay a transparent UIView on top of the UIWebView, re-implement the touch methods of UIResponder class (Ex: -touchesBegan:withEvent:) and then pass the events to the UIWebView. This method is explained in detail here. There are multiple problems with the method.
Copy/Selection stops working on UIWebView
We need to create a sub-class of UIWebView while Apple says we should not sub-class it.
A lot other UIWebView features stop working.
We ultimately found out that the right way to implement this is by
sub-classing UIWindow and re-implementing the -sendEvent: method. Here
is how you can do it. First, create a UIWindow sub-class
#import <UIKit/UIKit.h>
#protocol TapDetectingWindowDelegate
- (void)userDidTapWebView:(id)tapPoint;
#end
#interface TapDetectingWindow : UIWindow {
UIView *viewToObserve;
id <TapDetectingWindowDelegate> controllerThatObserves;
}
#property (nonatomic, retain) UIView *viewToObserve;
#property (nonatomic, assign) id <TapDetectingWindowDelegate> controllerThatObserves;
#end
Note that we have variables which tell us the UIView on which to
detect the events and the controller that receives the event
information. Now, implement this class in the following way
#import "TapDetectingWindow.h"
#implementation TapDetectingWindow
#synthesize viewToObserve;
#synthesize controllerThatObserves;
- (id)initWithViewToObserver:(UIView *)view andDelegate:(id)delegate {
if(self == [super init]) {
self.viewToObserve = view;
self.controllerThatObserves = delegate;
}
return self;
}
- (void)dealloc {
[viewToObserve release];
[super dealloc];
}
- (void)forwardTap:(id)touch {
[controllerThatObserves userDidTapWebView:touch];
}
- (void)sendEvent:(UIEvent *)event {
[super sendEvent:event];
if (viewToObserve == nil || controllerThatObserves == nil)
return;
NSSet *touches = [event allTouches];
if (touches.count != 1)
return;
UITouch *touch = touches.anyObject;
if (touch.phase != UITouchPhaseEnded)
return;
if ([touch.view isDescendantOfView:viewToObserve] == NO)
return;
CGPoint tapPoint = [touch locationInView:viewToObserve];
NSLog(#"TapPoint = %f, %f", tapPoint.x, tapPoint.y);
NSArray *pointArray = [NSArray arrayWithObjects:[NSString stringWithFormat:#"%f", tapPoint.x],
[NSString stringWithFormat:#"%f", tapPoint.y], nil];
if (touch.tapCount == 1) {
[self performSelector:#selector(forwardTap :) withObject:pointArray afterDelay:0.5];
}
else if (touch.tapCount > 1) {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(forwardTap :) object:pointArray];
}
}
#end
Implement the sendEvent method in the above way, and then you can send
back the information you want back to the controller.
There are few things that one needs to keep in mind. Make sure in your
MainWindow.xib file, the window is of type TapDetectingWindow and not
UIWindow. Only then all the events will pass through the above
re-implemented sendEvent method. Also, make sure you call [super
sendEvent:event] first and then do whatever you want.
Now, you can create your UIWebView in the controller class in the
following way
#interface WebViewController : UIViewController<TapDetectingWindowDelegate> {
IBOutlet UIWebView *mHtmlViewer;
TapDetectingWindow *mWindow;
}
- (void)viewDidLoad {
[super viewDidLoad];
mWindow = (TapDetectingWindow *)[[UIApplication sharedApplication].windows objectAtIndex:0];
mWindow.viewToObserve = mHtmlViewer;
mWindow.controllerThatObserves = self;
}
Remember you’ll need to write the method userDidTapWebView in your
controller class. This is the method that is called in order to send
the event information to the controller class. In our case above we
are sending the point in the UIWebView at which the user tapped.
You can very simply use a UITapGestureRecognizer to detect tap gestures on a UIWebView. You must implement a UIGestureRecognizerDelegate method to allow the simultaneous recognition however.
- (void)viewDidLoad{
[super viewDidLoad];
UITapGestureRecognizer *targetGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTap:)];
targetGesture.numberOfTapsRequired = 2;
targetGesture.delegate = self;
[self.webView addGestureRecognizer:targetGesture];
}
// called when the recognition of one of gestureRecognizer or otherGestureRecognizer would be blocked by the other
// return YES to allow both to recognize simultaneously. the default implementation returns NO (by default no two gestures can be recognized simultaneously)
//
// note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
NSLog(#"%#", otherGestureRecognizer);
//if you would like to manipulate the otherGestureRecognizer here is an example of how to cancel and disable it
if([otherGestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]){
UITapGestureRecognizer *tapRecognizer = (UITapGestureRecognizer*)otherGestureRecognizer;
if(tapRecognizer.numberOfTapsRequired == 2 && tapRecognizer.numberOfTouchesRequired == 1){
//this disalbes and cancels all other singleTouchDoubleTap recognizers
// default is YES. disabled gesture recognizers will not receive touches. when changed to NO the gesture recognizer will be cancelled if it's currently recognizing a gesture
otherGestureRecognizer.enabled = NO;
}
}
return YES;
}
-(void)handleTap:(id)sender{
}
I had several issues trying to use brian.clear's answer (copied from a extinct post by Mithin Kumar) in my iOS 5-7, universal, storyboard-based, totally ARC project so I had to make several changes. I also improved some things and made it easier to understand (at least for me). If you are having trouble trying to use that answer from 2009 maybe you should try my update. Detailed instructions:
1. Create a new TapDetectingWindow class
TapDetectingWindow.h
// Created by Cristian Perez <cpr#cpr.name>
// Based on https://stackoverflow.com/a/1859883/423171
#import <UIKit/UIKit.h>
#protocol TapDetectingWindowDelegate
- (void)userDidTapView:(CGPoint)tapPoint;
#end
#interface TapDetectingWindow : UIWindow
#property (nonatomic) UIView *tapDetectingView;
#property (nonatomic) id <TapDetectingWindowDelegate> tapDetectedDelegate;
#end
TapDetectingWindow.m
// Created by Cristian Perez <cpr#cpr.name>
// Based on https://stackoverflow.com/a/1859883/423171
#import "TapDetectingWindow.h"
#implementation TapDetectingWindow
#synthesize tapDetectingView;
#synthesize tapDetectedDelegate;
- (id)initWithFrame:(CGRect)frame
{
return [super initWithFrame:frame];
}
- (void)sendEvent:(UIEvent *)event
{
[super sendEvent:event];
if (tapDetectingView == nil || tapDetectedDelegate == nil)
{
return;
}
NSSet *touches = [event allTouches];
if (touches.count != 1)
{
return;
}
UITouch *touch = touches.anyObject;
if (touch.phase != UITouchPhaseEnded)
{
return;
}
if (touch.view != nil && ![touch.view isDescendantOfView:tapDetectingView])
{
return;
}
CGPoint tapPoint = [touch locationInView:tapDetectingView];
NSString *tapPointStr = NSStringFromCGPoint(tapPoint);
if (touch.tapCount == 1)
{
[self performSelector:#selector(notifyTap:) withObject:tapPointStr afterDelay:0.4];
// Make the afterDelay value bigger in order to have more chances of detecting a double tap and thus being able to cancel the single tap event, or make it smaller if you don't care about double taps and want to get the tap event as soon as possible
}
else if (touch.tapCount > 1)
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(notifyTap:) object:tapPointStr];
}
}
- (void)notifyTap:(NSString *)tapPointStr
{
CGPoint tapPoint = CGPointFromString(tapPointStr);
[tapDetectedDelegate userDidTapView:tapPoint];
}
#end
2. Check you have a window declared in your app delegate
You should have something like this in YourAppDelegate.h. Don't change the name of the property!
#interface YourAppDelegate : UIResponder <UIApplicationDelegate>
{
// ...
}
// ...
// The app delegate must implement the window property if it wants to use a main storyboard file
#property (nonatomic) UIWindow *window;
#end
3. Override the window property of your app delegate
Just like this, which should be in YourAppDelegate.m. Again, don't change the name of the method!
// Replace the default UIWindow property with a TapDetectingWindow
- (TapDetectingWindow *)window
{
static TapDetectingWindow *tapDetectingWindow = nil;
if (!tapDetectingWindow)
{
tapDetectingWindow = [[TapDetectingWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
}
return tapDetectingWindow;
}
4. Set the delegate protocol in your view controller
Be sure to adopt the tap handling protocol in your MainViewController.h
#import "TapDetectingWindow.h"
#interface MainViewController : UIViewController <TapDetectingWindowDelegate, ...>
{
// ...
}
// ...
#end
5. Set up the tap detecting window and tap event handler
Specify your webview (actually any UIView should work) and tap event handler in your view controller's (void)viewDidLoad method
- (void)viewDidLoad
{
// ...
// Allow tap detection in webview
TapDetectingWindow *tapDetectingWindow = (TapDetectingWindow*)[(YouTubeRPAppDelegate*)[[UIApplication sharedApplication] delegate] window];
tapDetectingWindow.tapDetectingView = self.webView; // Your UIWebView
tapDetectingWindow.tapDetectedDelegate = self;
}
6. Handle the tap event as you wish
Just implement the userDidTapView method in your view controller
- (void)userDidTapView:(CGPoint)tapPoint
{
NSLog(#"Tap detected in webview at %#", NSStringFromCGPoint(tapPoint));
}
Most of the approaches deal with a complicated pair of UIView and UIWebView subclasses and overrode -touchesBegan:withEvent: etc. methods.
This JavaScript-based approach intercepts touches on the web DOM itself, and it seems like a clever way to sidestep the more complex process. I haven't tried it myself, but I'm curious to know the results, if you give it a shot.
I'm not sure of the exact implementation details but you need to subclass UIWindow and override sendEvent:. Then you can capture tap events and handle them accordingly, before they get down to the web view. Hope this points you in the right direction!
Create a UIView sub class containing the whole UIWebView. Then the event hitTest will be fired on touching the webview. Note: Don't put anything to the container except the webView.
#interface myWebViewContainer : UIView
... ...
#end
Then override the hitTest event:
-(UIView*) hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
NSLog(#"Hit test %#", [event description]);
UIView * returnView = [super hitTest:point withEvent:event];
[delegate userDidTapWebView];// notify the delegate that UIWebView is being touched by some naughty user :P
return returnView;
}
A much simpler approach since iOS 3.2 is simply to use a UITapGestureRecognizer.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UITapGestureRecognizer* tapGestureRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(userDidTapWebView)] autorelease];
[self.pdfWebView addGestureRecognizer:tapGestureRecognizer];
}
- (void)userDidTapWebView {
NSLog(#"TAP");
}