我是Objective-C和Xcode的新手,我很难改变观点。我知道您可以使用UIScrollView
在图片视图之间滑动,但我只想向右滑动以更改视图,然后向左滑动即可返回。我的AppDelegate.h
和AppDelegate.m
尚未更改。 ViewController.h
和ViewController.m
如下:
ViewController.h:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
ViewController.m:
#import "ViewController.h"
#import "ViewController2.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//sets up gesture recognizer
UISwipeGestureRecognizer *swipeRightGesture=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
[self.view addGestureRecognizer:swipeRightGesture];
swipeRightGesture.direction=UISwipeGestureRecognizerDirectionRight;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)handleSwipeGesture:(UISwipeGestureRecognizer *)sender
{
NSUInteger touches = sender.numberOfTouches;
if (touches == 2)
{
if (sender.state == UIGestureRecognizerStateEnded)
{
ViewController2 *vc2 = [[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil];
[self.navigationController pushViewController:vc2 animated:YES];
}
}
}
@end
我还有ViewController2.h
和ViewController2.m
,我已将其链接到故事板中的第二个视图以及我已链接到上述handleSwipeGesture
方法的手势。
答案 0 :(得分:2)
- (void)viewDidLoad
{
[super viewDidLoad];
UISwipeGestureRecognizer *oneFingerSwipeLeft = [[UISwipeGestureRecognizer alloc]
initWithTarget:self
action:@selector(oneFingerSwipeLeft:)] ;
[oneFingerSwipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[[self view] addGestureRecognizer:oneFingerSwipeLeft];
}
- (void)oneFingerSwipeLeft:(UITapGestureRecognizer *)recognizer
{
NSLog(@"Swiped left");
// Add your navigation Code Here
}
如果你想用单指滑动,你可以使用它。如果你想添加两个手指轻扫添加你的
NSUInteger touches = sender.numberOfTouches;
if (touches == 2)
{
if (sender.state == UIGestureRecognizerStateEnded)
{
}
}
(void)onefingerSwipeLeft
方法
答案 1 :(得分:1)
- (IBAction)handleSwipeGesture:(UISwipeGestureRecognizer *)sender
不需要是IBAction,因为它没有连接到IBOutlet。它应该返回void
。
此外,一旦手势已被识别,您可以进行两次触摸,而不是检查手势的数量,而不是通过使用以下行来识别它:
swipeRightGesture.numberOfTouchesRequired = 2;
因此,方法-(void)handleSwipeGesture
不再需要参数,因此您可以从声明手势识别器的行中删除冒号。
最终代码可能与此类似:
UISwipeGestureRecognizer *swipeRightGesture=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture)];
swipeRightGesture.direction=UISwipeGestureRecognizerDirectionRight;
swipeRightGesture.numberOfTouchesRequired = 2;
[self.view addGestureRecognizer:swipeRightGesture];
...
...
- (void)handleSwipeGesture {
ViewController2 *vc2 = [[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil];
[self.navigationController pushViewController:vc2 animated:YES];
}