swift: 长按手势识别器不工作
swift: long press gesture reconizer doesn work
我有一个 UITableView
,我想为每一行添加 UILongPressGestureRecognizer
。
我尝试将识别器拖到 table 单元格上并为其引用一个动作,但从未调用过。
我也试过了
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ident, for: indexPath) as! TableViewCell
/*...*/
var longGesture = UILongPressGestureRecognizer(target: self, action: #selector(FilterPickerViewController.longPress))
longGesture.minimumPressDuration = 1
cell.leftLabel.addGestureRecognizer(longGesture)
return cell
}
@objc func longPress(_ sender: UILongPressGestureRecognizer) {
print("press")
}
但这也没有用。我做错了什么?
您必须将长按手势识别器添加到 table 视图:
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 2.0; //seconds
lpgr.delegate = self;
[self.myTableView addGestureRecognizer:lpgr];
[lpgr release];
然后在手势处理程序中:获取单元格索引:-
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
CGPoint p = [gestureRecognizer locationInView:self.myTableView];
NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:p];
if (indexPath == nil) {
NSLog(@"long press on table view but not on a row");
} else if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
NSLog(@"long press on table view at row %ld", indexPath.row);
} else {
NSLog(@"gestureRecognizer.state = %ld", gestureRecognizer.state);
}
}
我有一个 UITableView
,我想为每一行添加 UILongPressGestureRecognizer
。
我尝试将识别器拖到 table 单元格上并为其引用一个动作,但从未调用过。
我也试过了
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ident, for: indexPath) as! TableViewCell
/*...*/
var longGesture = UILongPressGestureRecognizer(target: self, action: #selector(FilterPickerViewController.longPress))
longGesture.minimumPressDuration = 1
cell.leftLabel.addGestureRecognizer(longGesture)
return cell
}
@objc func longPress(_ sender: UILongPressGestureRecognizer) {
print("press")
}
但这也没有用。我做错了什么?
您必须将长按手势识别器添加到 table 视图:
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 2.0; //seconds
lpgr.delegate = self;
[self.myTableView addGestureRecognizer:lpgr];
[lpgr release];
然后在手势处理程序中:获取单元格索引:-
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
CGPoint p = [gestureRecognizer locationInView:self.myTableView];
NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:p];
if (indexPath == nil) {
NSLog(@"long press on table view but not on a row");
} else if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
NSLog(@"long press on table view at row %ld", indexPath.row);
} else {
NSLog(@"gestureRecognizer.state = %ld", gestureRecognizer.state);
}
}