tableView中的事件处理

Sal*_*maz 2 uitableview ios uievent swift

我正在尝试做的是处理触摸事件,以便当我触摸屏幕时,我想采取一些行动.例如改变背景颜色我试过的事情://我是子视图表视图控制器

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
     tableView.backgroundColor = UIColor.orangeColor()
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,我怀疑tvc可能不是第一响应者,因此表视图处理触摸事件.所以我试过:

 override func viewDidLoad() {
     super.viewDidLoad()
     tableView.resignFirstResponder()    
}
Run Code Online (Sandbox Code Playgroud)

还尝试过:

override func becomeFirstResponder() -> Bool {
    return true
}

override func canBecomeFirstResponder() -> Bool {
    return true
}
Run Code Online (Sandbox Code Playgroud)

他们都没有工作.我该如何处理事件?我错过了什么?

编辑

根据本机swift代码选择的答案:

override func viewDidLoad() {
        super.viewDidLoad()

        var tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tap:")
        tapGestureRecognizer.cancelsTouchesInView = true
        self.tableView.addGestureRecognizer(tapGestureRecognizer)




    }

    func tap(recognizer: UITapGestureRecognizer) {
        if recognizer.state == UIGestureRecognizerState.Ended {
            var tapLocation  = recognizer.locationInView(self.tableView)
            var tapIndexPath : NSIndexPath? = self.tableView.indexPathForRowAtPoint(tapLocation)

            if let index = tapIndexPath  {

                self.tableView(self.tableView, didSelectRowAtIndexPath: index)
            } else {
                self.tableView.backgroundColor = UIColor.orangeColor()
            }
        }

    }
Run Code Online (Sandbox Code Playgroud)

Pau*_*uls 5

如果您想对整个视图中的触摸做出反应,而不仅仅是单元格,请在viewDidLoad中添加一个点击手势识别器:

- (void)addTapGestureForListTable {
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userTappedOnView:)];
    tapGestureRecognizer.cancelsTouchesInView = YES;
    [self.tableView addGestureRecognizer:tapGestureRecognizer];
}
Run Code Online (Sandbox Code Playgroud)

然后实现userTappedOnView方法.如果你想区分细胞上的触摸,可以这样实现:

- (void)userTappedOnView:(UITapGestureRecognizer *)recognizer {
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        CGPoint tapLocation = [recognizer locationInView:self.tableView];
        NSIndexPath *tapIndexPath = [self.tableView indexPathForRowAtPoint:tapLocation];
        if (tapIndexPath) {
            [self tableView:self.tableView didSelectRowAtIndexPath:tapIndexPath];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要对单元格上的触摸作出反应,则必须使tableView的委托指向控制器.在viewDidLoad中:

self.tableView.delegate = self;
Run Code Online (Sandbox Code Playgroud)

然后实现该方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
Run Code Online (Sandbox Code Playgroud)