[英]How to swap views using a swipe gesture XCode
我正在使用XCode为iOS平台开发一个Cocoa touch应用程序但是却无法找到如何实现一个滑动手势,允许用户向左或向右滑动手指以更改为新的ViewController
(nib / xib文件) )。 我已经使用按钮和模态转换完成了swapView IBAction
,我已经阅读了Apple的TouchGestureRecognizer
但我不知道如何实现允许视图更改的滑动操作。
我不想使用滚动视图,因为我有几十个视图控制器,我希望用户能够轻扫。
这是一个例子:
First View Controller.xib:SwipeRight-转到第二个View Controller.xib
第二视图Controller.xib:
SwipeLeft-转到第一个View Controller.xib
SwipeRight-转到第三个View Controller.xib
等等
我之前没有使用UISwipe / Touch Gestures,但是我使用IBAction
方法使用带模态转换的按钮切换视图(见下文):
-(IBAction)swapViews; {
SecondViewController *second2 =[[SecondViewController alloc initWithNibName:@"SecondViewController" bundle:nil];
second2.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:second2 animated:YES];
[second2 release];
}
使用滑动来执行不同格式的类似方法吗? 如果是这样,我该如何排序并格式化它。
谢谢
编辑 - 回答每个问题的评论
将它放在viewDidLoad中
UISwipeGestureRecognizer *swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeftDetected:)];
swipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeRecognizer];
[swipeRecognizer release];
然后添加一个选择器,方法是将以下代码粘贴到主...
- (IBAction)swipeLeftDetected:(UIGestureRecognizer *)sender {
NC2ViewController *second2 =[[NC2ViewController alloc] initWithNibName:@"NC2ViewController" bundle:nil];
second2.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:second2 animated:YES];
[second2 release];
}
然后确保导入要交换使用的otherViewController
#import "SecondViewController"
在主文件的顶部。 希望这可以帮助。
结束编辑
这听起来像是使用UIGestureRecognizer或更具体地说是UISwipeGestureRecognizer的最佳时机 。
有关如何使用它们的更多信息,请阅读“事件处理指南”的“ 手势识别器”部分。
让我们假设你想向左滑动以显示右边的另一个视图。
在故事板中,拖放滑动手势识别器。 它将在视图控制器下方生成一个图标; 拖动此图标并将其拖放到要导航到的ViewController上。 这将添加一个segue,选择自定义segue。 然后创建一个UIStoryboardSegue类。 添加以下代码:
- (void)perform {
UIViewController* source = (UIViewController *)self.sourceViewController;
UIViewController* destination = (UIViewController *)self.destinationViewController;
CGRect sourceFrame = source.view.frame;
sourceFrame.origin.x = -sourceFrame.size.width;
CGRect destFrame = destination.view.frame;
destFrame.origin.x = destination.view.frame.size.width;
destination.view.frame = destFrame;
destFrame.origin.x = 0;
[source.view.superview addSubview:destination.view];
[UIView animateWithDuration:0.5
animations:^{
source.view.frame = sourceFrame;
destination.view.frame = destFrame;
}
completion:^(BOOL finished) {
UIWindow *window = source.view.window;
[window setRootViewController:destination];
}];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.