Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton does not work when it in UIScrollView

Tags:

My structure of views:

UITableView   UITableViewCell     UIScrollView       CustomView         UIButton 

The problem is UIButton doesn't work when I touch it. I create it with code:

btn = [[UIButton alloc] init]; [btn setImage:image forState:UIControlStateNormal]; [btn addTarget:self action:@selector(tileTouchUpInside) forControlEvents:UIControlEventTouchUpInside]; btn.layer.zPosition = 1; [self addSubview:btn]; 

I've also add this:

scroll.delaysContentTouches = NO; scroll.canCancelContentTouches = NO; 

But my button doesn't work anyway. I can't cancelContentTouches or set delay for UITableView because if I set it, UITableView stop scrolling verticaly.

Thanks for any help!

like image 202
George Avatar asked May 20 '13 12:05

George


2 Answers

Create a subclass of UIScrollview with

- (BOOL)touchesShouldCancelInContentView:(UIView *)view {   return NO; } 

If you are not getting that message, set:

scrollView.delaysContentTouches = NO; 

The problem is because of the way touchesShouldCancelInContentView behaves by default, it returns NO only if the subview is an UIControl, but your button is hidden inside the CustomView which isn't.

like image 87
Max Huk Avatar answered Sep 22 '22 18:09

Max Huk


Came across the same scenario. UIScrollView in separate class and adding button through a custom view. 'NSNotificationCenter' helped me solving the issue. Sample code:

-(void)tileTouchUpInside:(id)sender {         NSDictionary *dict=[NSDictionary dictionaryWithObject:@"index" forKey:@"index"];      [[NSNotificationCenter defaultCenter]postNotificationName:@"Action" object:nil userInfo:dict]; } 

In the class containing Scroll View:

- (void)viewDidLoad {     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doAction:) name:@"Action" object:nil]; } -(void)doAction:(NSNotification *) notification {     NSString* value =[notification.userInfo valueForKey:@"index"];     // ....... } 

Enable userInteraction for scroll view, custom view and button.

like image 28
Siva Avatar answered Sep 22 '22 18:09

Siva