[英]UIView in UIScrollview. frame.origin not changing on scrolling, can't detect collision
我的屏幕上包含:
UIScrollView與UIView A重疊(直到大約一半),允許我“拖動” UIView B並將其與UIView A重疊。這樣,當我放開它時,UIView B可以很好地彈回它原始位置(我不希望將其從屏幕的起點一直拖到UIView A上)
現在,我試圖在UIView重疊時檢測到碰撞。 但是,從未檢測到。 我正在使用convertRect:toView:在同一系統上獲取坐標,但是通過在touchesMoved中跟蹤UIView B的坐標,我看到“拖動”(確實滾動UIScrollView)不會影響其框架的原點坐標。 它們的觸動開始與每次觸動時一樣。
我假設這是因為UIViewB並沒有真正移動到任何地方,UIScrollView是,這意味着UIView的原點始終是相同的,即使它的絕對坐標不是。 關於如何處理這個有什么建議嗎?
當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號則是它開始與黑框重疊的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.