天天看點

IOS 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.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];
}      

注意: 我們必須添加一個命名為"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
}      

繼續閱讀