2011年12月6日 星期二

iOS - Training (11) - UIScrollView

用於瀏覽內容畫面比Device畫面還大時,可以藉由托拉、放大、縮小的方式調整畫面。
參數:
  • contentSize: 決定UIScrollView可以scroll的範圍,通常UIScrollView的size會比contentSize來的小。
  • contentOffset: UIScrollView左上角的點與content邊界的遍移值。在托拉UIScrollView時,此值會一直變化。
ViewController.h
加入UIScrollView與UIImageView元件
@interface ViewController : UIViewController

{
    IBOutlet UIScrollView *myScroll;
    UIImageView* contentImgView;
}
@end

ViewController.m

- (void)viewDidLoad

{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    int imgWidth = 352;
    int imgHeight = 500;
    
    contentImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"minami.jpg"]];
    contentImgView.frame = CGRectMake(0.0, 0.0, imgWidth, imgHeight);
    
    myScroll.contentSize = CGSizeMake(imgWidth, imgHeight);
    [myScroll addSubview:contentImgView];
    
    // 加入放大縮小功能
    myScroll.delegate = self; // 會去調用viewForZoomingInScrollView方法
    myScroll.maximumZoomScale = 1;
    myScroll.minimumZoomScale = myScroll.bounds.size.height / contentImgView.bounds.size.height;
    
    // 畫面起始大小與內容大小一樣
    [myScroll zoomToRect:CGRectMake(0.0, 0.0, imgWidth, imgHeight) animated:YES];
}

// 加入此方法才會被調用放大縮小功能
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return contentImgView;
}

分頁效果 (類似Android的Gallery)-----

- (void)viewDidLoad

{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    int imgNum = 3;
    float imgWidth = 240;
    float imgheight = 240;
    
    myScroll.contentSize = CGSizeMake(imgNum*imgWidth, imgheight);
    
    for(int i = 0;i < imgNum;i++)
    {
        UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"page%d.jpg", i+1]]];
        imageView.frame = CGRectMake(i*imgWidth, 0, imgWidth, imgheight);
        
        [myScroll addSubview:imageView];
    }
    myScroll.pagingEnabled = YES; // 分頁效果
    myScroll.delegate = self; // 調用UIScrollViewDelegate裡的scrollViewDidScroll方法
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGRect bounds = scrollView.bounds;
    NSLog(@"Bounds %f, %f, %f, %f", bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
}
-----

資料出處《Object-C與iOS開發入門》

沒有留言:

張貼留言