捲動檢視用於顯示內容超過螢幕大小。它可以包含所有其他使用者介面元素,如影象檢視,標籤,文字檢視,甚至是另一個捲動檢視本身。
重要的屬性
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 }
現在,當我們執行程式時,我們會得到下面的輸出。一旦捲動捲動檢視,將能夠看到影象的其餘部分。