UIGestureRecognizer和UITableViewCell的问题
-
25-09-2019 - |
题
我附上一个UISwipeGestureRecognizer
到UITableViewCell
在cellForRowAtIndexPath:
方法如下所示:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UISwipeGestureRecognizer *gesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)];
gesture.direction = UISwipeGestureRecognizerDirectionRight;
[cell.contentView addGestureRecognizer:gesture];
[gesture release];
}
return cell;
}
然而,didSwipe
方法总是得到成功的滑动调用两次。我最初以为这是因为手势开始和结束,但如果我注销gestureRecognizer本身,它们都在“结束”状态:
-(void)didSwipe:(UIGestureRecognizer *)gestureRecognizer {
NSLog(@"did swipe called %@", gestureRecognizer);
}
控制台:
2011-01-05 12:57:43.478 App[20752:207] did swipe called <UISwipeGestureRecognizer: 0x5982fa0; state = Ended; view = <UITableViewCellContentView 0x5982c30>; target= <(action=didSwipe:, target=<RootViewController 0x5e3e080>)>; direction = right>
2011-01-05 12:57:43.480 App[20752:207] did swipe called <UISwipeGestureRecognizer: 0x5982fa0; state = Ended; view = <UITableViewCellContentView 0x5982c30>; target= <(action=didSwipe:, target=<RootViewController 0x5e3e080>)>; direction = right>
我真的不知道为什么。我试着显然检查结束的状态,但就是没有帮助,因为他们都来作为“端”反正...任何想法?
解决方案
,而不是直接加入手势识别到细胞中,可以在viewDidLoad
它添加到tableview中。
在didSwipe
-方法可以确定受影响IndexPath和细胞如下:
-(void)didSwipe:(UIGestureRecognizer *)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
CGPoint swipeLocation = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:swipeLocation];
UITableViewCell* swipedCell = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
// ...
}
}
其他提示
有将与应用程序委托工作
- (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
// code
}
我有同样的问题,并通过勾选在表视图属性“滚动启用”解决它。
我的表视图不需要滚动,所以它不会影响任何其他方式的应用程序,现在除了我轻扫手势后没有得到第一反应迟钝水龙头。
在AwakeFromNib方法添加手势,没有任何问题的工作原理。
class TestCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
let panGesture = UIPanGestureRecognizer(target: self,
action: #selector(gestureAction))
addGestureRecognizer(panGesture)
}
@objc func gestureAction() {
print("gesture action")
}
}
不隶属于 StackOverflow