现在我正在开发一个使用UITableviewCell子类的iPad应用程序,它使用UIPanGestureRecognizer向左和向右滑动,但是它只向右滑动并且向左滑动...这是我正在使用的代码:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self)
{
// Initialization code
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
pan.delegate = self;
[self addGestureRecognizer:pan];
}
return self;
}
这是我的handlePan:方法,
CGPoint translation = [gesture locationInView:self];
self.center = CGPointMake(self.center.x + translation.x,
self.center.y);
if (self.center.x > 700) {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:self.tag],@"number",nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"right" object:nil userInfo:dic];
dic = nil;
}
if (self.center.x < 0){
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:self.tag],@"number",nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"left" object:nil userInfo:dic];
dic = nil;
NSLog(@"Left Called");
}
[gesture setTranslation:CGPointZero inView:self];
无论我尝试什么,我似乎无法让控制台说“左叫”,即细胞向左滑动。我真的在努力解决这个问题,并希望得到任何帮助。
答案 0 :(得分:2)
诀窍是对锅的改变状态作出反应,中心计算可以简单得多......
- (void)handlePan:(UIPanGestureRecognizer *)gesture {
if ((gesture.state == UIGestureRecognizerStateChanged) ||
(gesture.state == UIGestureRecognizerStateEnded)) {
CGPoint newCenter = CGPointMake([gesture locationInView:self.superview].x, self.center.y);
self.center = newCenter;
// To determine the direction of the pan, check the sign of translation in view.
// This supplies the cumulative translation...
if ([gesture translationInView:self.superview].x > 0) {
NSLog(@">>>");
} else {
NSLog(@"<<<");
}
}
}
答案 1 :(得分:1)
我认为你决定左/右的方式可能存在缺陷。
CGPoint translation = [gesture locationInView:self];
self.center = CGPointMake(self.center.x + translation.x,
self.center.y);
self.center.x将始终为正,因为“translation”是视图中的正位置。 您可能想要跟踪原始触摸位置,然后将其与滑动/移动时的位置进行比较。尝试这样的事情:
- (void)handlePan:(UIPanGestureRecognizer *)panRecognizer {
if (panRecognizer.state == UIGestureRecognizerStateBegan)
{
// create a local property for the original point and assign the position on first touch
self.originalPanTouchPoint = [panRecognizer locationInView:self.view];
// create a local property for cell's center prior to pan
self.initialCellCenter = self.center;
} else {
CGPoint currentTouchPoint = [panRecognizer locationInView:self.view];
CGFloat xTranslation = self.originalPanTouchPoint.x - currentTouchPoint.x;
self.center = CGPointMake(self.initialCellCenter.x + xTranslation, self.initialCellCenter.y);
}
}