如何为UIScrollView启用方向锁?

我有一个内置UIViewUIScrollView 。 我想锁定x轴,以便视图只垂直滚动。 如何启用方向锁定?

首先,将UIScrollView的“contentSize”设置为宽度等于或小于UIScrollView框架的宽度。

接下来,将UIScrollView的“alwaysBounceHorizo​​ntal”设置为NO。 这将阻止滚动视图“橡皮筋”,即使你告诉它没有更多的水平内容可以显示。

 UIScrollView *scrollView; CGSize size = scrollView.contentSize; size.width = CGRectGetWidth(scrollView.frame); scrollView.contentSize = size; scrollView.alwaysBounceHorizontal = NO; 

滚动视图中的实际内容并不重要。

您将touchesEnded:withEvent: UIScrollView并覆盖touchesBegan:withEvent:方法, touchesMoved:withEvent:方法和touchesEnded:withEvent:方法。

您将使用这些方法以及触摸的起点和终点来计算发生了什么类型的触摸事件:是简单的点击,还是水平或垂直滑动?

如果是水平滑动,则取消触摸事件。

在这里查看源代码 ,了解如何开始。

 #import  @interface DemoButtonViewController : UIViewController  @property (nonatomic, strong) UIScrollView *filterTypeScrollView; @property (nonatomic, strong) UIBarButtonItem *lockButton; - (void)lockFilterScroll:(id)sender; @end #import "DemoButtonViewController.h" @implementation DemoButtonViewController @synthesize filterTypeScrollView; @synthesize lockButton; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor darkGrayColor]; self.filterTypeScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 130, self.view.frame.size.width, 320)]; filterTypeScrollView.contentSize = CGSizeMake(self.view.frame.size.width*4, 320); filterTypeScrollView.pagingEnabled = YES; filterTypeScrollView.delegate = self; [self.view addSubview:filterTypeScrollView]; UIToolbar *lockbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 450, self.view.frame.size.width, 30)]; lockbar.barStyle = UIBarStyleBlackTranslucent; self.lockButton = [[UIBarButtonItem alloc] initWithTitle:@"Lock Filter Scroll" style:UIBarButtonItemStylePlain target:self action:@selector(lockFilterScroll:)]; [lockbar setItems:[NSArray arrayWithObjects:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],lockButton,nil]]; [self.view addSubview:lockbar]; } - (void)viewDidUnload { [super viewDidUnload]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } - (void)lockFilterScroll:(id)sender { filterTypeScrollView.scrollEnabled = !filterTypeScrollView.scrollEnabled; if (filterTypeScrollView.scrollEnabled) { [lockButton setTitle:@"Lock Filter Scroll"]; } else { [lockButton setTitle:@"Unlock Filter Scroll"]; } } @end