iOS - 滚动视图
-
滚动视图的使用
滚动视图用于显示超过屏幕大小的内容。它可以包含所有其他 UI 元素,如图像视图、标签、文本视图甚至另一个滚动视图本身。 -
重要属性
- 内容大小
- 内容插入
- 内容偏移
- 代表
-
重要方法
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated - (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated
-
重要的委托方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate - (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
更新 ViewController.h 如下 -通过添加使您的类符合滚动视图委托协议 < UIScrollViewDelegate> 并声明一个滚动视图实例,如下所示 ViewController.h.#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIScrollViewDelegate> { UIScrollView *myScrollView; } @end
-
添加自定义方法 addScrollView
-(void)addScrollView { myScrollView = [[UIScrollView alloc]initWithFrame: CGRectMake(20, 20, 280, 420)]; myScrollView.accessibilityActivationPoint = CGPointMake(100, 100); imgView = [[UIImageView alloc]initWithImage: [UIImage imageNamed:@"AppleUSA.jpg"]]; [myScrollView addSubview:imgView]; myScrollView.minimumZoomScale = 0.5; myScrollView.maximumZoomScale = 3; myScrollView.contentSize = CGSizeMake(imgView.frame.size.width, imgView.frame.size.height); myScrollView.delegate = self; [self.view addSubview:myScrollView]; }
Note −我们必须将名为“AppleUSA1.jpg”的图像添加到我们的项目中,这可以通过将图像拖到我们的导航器区域来完成,其中列出了我们的项目文件。图像的分辨率应高于设备才能看到图像滚动。 -
在 ViewController.m 中实现 scrollView 委托
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return imgView; } -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { NSLog(@"Did end decelerating"); } -(void)scrollViewDidScroll:(UIScrollView *)scrollView { // NSLog(@"Did scroll"); } -(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { NSLog(@"Did end dragging"); } -(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView { NSLog(@"Did begin decelerating"); } -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { NSLog(@"Did begin dragging"); }
更新 ViewController.m 中的 viewDidLoad 如下 -(void)viewDidLoad { [super viewDidLoad]; [self addScrollView]; //Do any additional setup after loading the view, typically from a nib }
-
输出
当我们运行应用程序时,我们将得到以下输出。滚动滚动视图后,您将能够看到图像的其余部分。