سؤال

I want to know how can I add UIControlEvent to a UITableViewCell? I cannot use the method addTarget:action:forControlEvents on a UITableViewCell. I cannot use didSelectCellAtIndexPath: because I need to know for UIControlEventTouchDown and UIControlEventTouchUpInside. How can I achieve this?

Thanks!

هل كانت مفيدة؟

المحلول

EDIT: Another option is to expose the UIButton property on your cell publicly, and in cellForRowAtIndexPath: call addTarget:action:forControlEvent: on the cell's button, passing self and the method on your view controller that you wish to be called on touch. This precludes any need for a delegate protocol. The only catch is that before you set the target-action on the cell's button, make sure to call:

[cell.button removeTarget:nil 
               action:NULL 
     forControlEvents:UIControlEventAllEvents]; 

Since the cell (and it's button) is reused, you need to call this is to make sure you're not stacking target-actions on the button.

نصائح أخرى

I think that the cleanest solution is to define a custom UIGestureRecognizer and add it to the UITableViewCell.

MDGestureRec.h

#import <UIKit/UIKit.h>
#import <UIKit/UIGestureRecognizerSubclass.h>

@interface MDGestureRec : UIGestureRecognizer

- (void)reset;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

@end

// ------

MDGestureRec.m

#import "MDGestureRec.h"

@implementation MDGestureRec

- (void)reset { }
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"touches %@", [touches description]);
    NSLog(@"touchesBegan %@", [event description]);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { }
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { }
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { }

@end

// ------

    MDGestureRec *g = [[MDGestureRec alloc] init];

    [cell addGestureRecognizer:g];
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top