iOS - Scroll View(滾動視圖)
使用Scroll View
滾動視圖用於顯示內容超過屏幕大小。它可以包含所有其他用戶界面元素,如圖像視圖,標籤,文本視圖,甚至是另一個滾動視圖本身。
重要的屬性
contentSize
contentInset
contentOffset
delegate
重要的方法
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
- (void)setContentOffset:(CGYiibai)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 如下:
讓類符合滾動視圖委託協議通過添加
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIScrollViewDelegate> { UIScrollView *myScrollView; } @end
添加一個自定義的方法addScrollView
-(void)addScrollView{ myScrollView = [[UIScrollView alloc]initWithFrame: CGRectMake(20, 20, 280, 420)]; myScrollView.accessibilityActivationYiibai = CGYiibaiMake(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]; }
注意事項:
我們必須命名爲 「AppleUSA1.jpg」,我們可以通過拖動圖像到我們的導航區域,項目文件列出的項目中添加圖像。圖像的分辨率高於設備看到的圖像的滾動。
實現滾動視圖在 ViewController.m 委託
-(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 }
輸出
現在,當我們運行程序時,我們會得到下面的輸出。一旦滾動滾動視圖,將能夠看到圖像的其餘部分。