當 UILongPressGestureRecognizer 開始識別時,我想將視圖移動到另一個視圖,但是當這種情況發生時,狀態變為取消。
if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan) {
[cellView removeFromSuperview];
[self.anotherView addSubview:cellView];
}
有沒有辦法保留手勢識別器?
uj5u.com熱心網友回復:
洗掉這一行:
[cellView removeFromSuperview];
當你執行:
[self.anotherView addSubview:cellView];
UIKit 會自動將其cellView 從當前的 superview 中移出并將其添加到anotherView.
這應該可以防止丟失手勢識別器的狀態。
這是一個簡單的例子:
#import "LongPressViewController.h"
@interface LongPressViewController ()
{
UIView *blueView;
UIView *redView;
UIView *yellowView;
}
@end
@implementation LongPressViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = UIColor.systemBackgroundColor;
blueView = [UIView new];
redView = [UIView new];
yellowView = [UIView new];
blueView.backgroundColor = UIColor.systemBlueColor;
redView.backgroundColor = UIColor.systemRedColor;
yellowView.backgroundColor = UIColor.systemYellowColor;
blueView.frame = CGRectMake(80, 100, 240, 240);
redView.frame = CGRectOffset(blueView.frame, 0, 260);
yellowView.frame = CGRectMake(20, 20, 80, 80);
[blueView addSubview:yellowView];
[self.view addSubview:blueView];
[self.view addSubview:redView];
UILongPressGestureRecognizer *g = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(lpHandler:)];
[yellowView addGestureRecognizer:g];
}
- (void)lpHandler:(UILongPressGestureRecognizer *)longPressGestureRecognizer {
CGPoint p = [longPressGestureRecognizer locationInView:yellowView];
switch (longPressGestureRecognizer.state) {
case UIGestureRecognizerStateBegan:
[redView addSubview:yellowView];
break;
case UIGestureRecognizerStateChanged:
NSLog(@"Changed: %@", [NSValue valueWithCGPoint:p]);
break;
case UIGestureRecognizerStateEnded:
NSLog(@"Ended");
break;
default:
break;
}
}
@end
yellowView將作為 的子視圖開始blueView。當你長按時,它會“跳轉”到 - 并成為 - 的子視圖redView。
保持觸摸向下,當您拖動時,您將看到觸摸位置的連續記錄(相對于yellowView)。
當您松開觸摸時,我們會記錄“已結束”
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/462956.html
