当 scrollView.frame.origin.x + viewB.frame.size.width + scrollView.contentOffset.x >= viewA.frame.origin.x 会有重叠
编辑后:
我无法让滚动视图工作,所以我尝试了另一种效果很好的方法。我没有使用滚动视图,而是使用了一个带有背景颜色的矩形视图,并在其中添加了蓝色方块。我在 IB 中给蓝色方块设置了宽度和高度,将它置于细长视图的中心(在 y 方向),并且对该长视图的左侧有另一个约束。IBOutlet leftCon 连接到该约束。然后,我使用此代码拖动它,并在我放手时让它返回:
#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@property (strong,nonatomic) UIPanGestureRecognizer *panner;
@property (strong,nonatomic) IBOutlet NSLayoutConstraint *leftCon;
@property (strong,nonatomic) CADisplayLink *displayLink;
@end
@implementation ViewController {
IBOutlet UIView *blueSquare;
}
-(void)viewDidLoad {
self.panner = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
[blueSquare addGestureRecognizer:self.panner];
}
- (void)handlePanGesture:(UIPanGestureRecognizer *)sender {
CGPoint translate = [sender translationInView:self.view];
if (self.leftCon.constant <160)
if (self.leftCon.constant > 100) NSLog(@"Bang! We have a collision");
self.leftCon.constant = translate.x;
if (sender.state == UIGestureRecognizerStateEnded){
[self startDisplayLink];
}
}
-(void)startDisplayLink {
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(bounceBack:)];
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void)stopDisplayLink {
[self.displayLink invalidate];
self.displayLink = nil;
}
-(void)bounceBack:(CADisplayLink *) link {
self.leftCon.constant -= 12;
if (self.leftCon.constant < 2) {
[self stopDisplayLink];
self.leftCon.constant = 2;
}
}
翻译代码中的数字(160 和 100)是通过记录凭经验确定的。数字 160 防止它离开长视图的右边缘,数字 100 是它开始与黑框重叠的地方。