5

正如问题所述,我想为 UITableViewCell 上的点击和长按实现两种不同的操作。

我认为我必须在每个阶段取消选择该行并且在此处不放置任何函数:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

然后从情节提要添加点击手势,但是当我将动作拖动到原型单元格时情节提要给我一个错误。提示?

4

3 回答 3

14

尝试这个 -

在您的cellForRowAtIndexPath方法中,您可以分别添加点击手势和长按手势,然后实现它们。这样一来,您的didselect功能将不是必需的,您也不必做deSelect任何事情。

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cellTapped:)];
    tapGestureRecognizer.numberOfTapsRequired = 1;
    tapGestureRecognizer.numberOfTouchesRequired = 1;
    cell.tag = indexPath.row;
    [cell addGestureRecognizer:tapGestureRecognizer];


UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
                         initWithTarget:self action:@selector(handleLongPress:)];
        lpgr.minimumPressDuration = 1.0; //seconds
        [cell addGestureRecognizer:lpgr];

cell.selectionStyle = UITableViewCellSelectionStyleNone;

现在,

-(void)handleLongPress:(UILongPressGestureRecognizer *)longPress
{
    // Your code here
}

-(void)cellTapped:(UITapGestureRecognizer*)tap
{
    // Your code here
}
于 2013-08-26T09:44:49.897 回答
0

您可以使用上面发布的 UITableViewDelegate 方法处理单击操作,

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

要在您的 UITableViewCell 上执行 UILongPressGestureRecognizer 请遵循此说明

希望有帮助。

于 2013-08-26T05:55:04.307 回答
0

斯威夫特

像这样定义手势:

fileprivate func addGestures(inCell cell: UITableViewCell, withIndexPath indexPath: IndexPath) {
    let tapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(cellTapped))
    tapGestureRecognizer.numberOfTapsRequired = 1
    tapGestureRecognizer.numberOfTouchesRequired = 1
    cell.addGestureRecognizer(tapGestureRecognizer)

    let lpgr = UILongPressGestureRecognizer.init(target: self, action: #selector(cellLongPressed))
    lpgr.minimumPressDuration = 1.0
    cell.addGestureRecognizer(lpgr)

    cell.tag = indexPath.row

    cell.selectionStyle = .none
}

@objc fileprivate func cellTapped(_ gesture: UITapGestureRecognizer) {
     //Do whatever you want to!
}

@objc fileprivate func cellLongPressed(_ gesture: UILongPressGestureRecognizer) {
    if gesture.state == .began {
         //Do whatever you want to!
    }
}

并添加这样的手势:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = (tableView.dequeueReusableCell(withIdentifier: "CellIdentifier") as! UITableViewCell)

    self.addGestures(inCell: cell, withIndexPath: indexPath)
}
于 2018-06-06T05:41:56.187 回答