如何touchesBegan: withEvent:
在 UITableViewController 类中使用方法?
UITableViewController 是 UIViewController 类的子类。那么为什么该方法在 UITableViewController 中不起作用呢?
如何touchesBegan: withEvent:
在 UITableViewController 类中使用方法?
UITableViewController 是 UIViewController 类的子类。那么为什么该方法在 UITableViewController 中不起作用呢?
I had a similar problem, and found a different approach that doesn't involve subclassing UITableView. Another way to do this is to add a gesture recognizer to the UITableViewController's view.
I put this code in the UITableViewController's viewDidLoad:
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self.view addGestureRecognizer:tap];
And implemented the event handler:
- (void)handleTap:(UITapGestureRecognizer *)recognizer
{
// your code goes here...
}
I know this solution doesnt use touchesBegan, but I found it was a simple solution to the same problem.
touchesBegan 除了是 UIViewController 方法之外,也是 UIView 方法。
要覆盖它,您需要继承 UIView 或 UITableView 而不是控制器。
Here is a UITableView subclass solution that worked for me. Make a subclass of UITableView and override hitTest:withEvent: as below:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
static UIEvent *e = nil;
if (e != nil && e == event) {
e = nil;
return [super hitTest:point withEvent:event];
}
e = event;
if (event.type == UIEventTypeTouches) {
NSSet *touches = [event touchesForView:self];
UITouch *touch = [touches anyObject];
if (touch.phase == UITouchPhaseBegan) {
NSLog(@"Touches began");
}
}
return [super hitTest:point withEvent:event];
}
touchesBegan 是 UIView 和 UITableViewCell 方法,而不是 UIViewController 和 UITableViewController 方法。因此,您可以为 UITableViewCell 创建自定义类,它可以识别触摸事件并为我工作的触摸委托。
//TableViewCell.h
#import <UIKit/UIKit.h>
@class Util;
@interface TableViewCell : UITableViewCell {
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;
@end
//TableViewCell.m
#import "TableViewCell.h"
@implementation TableViewCell
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier format:(NSString*)ec_format{
if (self) {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//you receive touch here
NSLog(@"Category Touch %@",self.frame);
}
祝你有美好的一天
IN SWIFT - I came across this question while searching for a Swift 2 solution. The answer posted by @Steph Sharp helped me work out the the problem in Swift so I though I'de post it on here. Here you go:
class CalcOneTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTap:")
self.view.addGestureRecognizer(tap)
}
Function
func handleTap(recognizer: UITapGestureRecognizer) {
// Do your thing.
}