固定UIScrollView滑動的方向


固定UIScrollView滑動的方向

一般而言,我們通過這兩個參數CGRectMake以及contentSize就可以自動的讓UIScrollView只往一個方向滾動.但我遇到過非常奇葩的情況,那就是即使設置的CGRectMake以及contentSize沒有一點點問題,這個UIScrollView也能夠上下左右滾動-_-!!.

為了不依賴於CGRectMake以及contentSize,我們可以通過在代理方法scrollViewDidScroll:中進行限制即可.

沒有限制之前的效果:

源碼:

//
//  RootViewController.m
//  BUG
//
//  Copyright (c) 2014年 Y.X. All rights reserved.
//

#import "RootViewController.h"

@interface RootViewController ()<UIScrollViewDelegate>

{
    UIScrollView    *_showView;
}

@end

@implementation RootViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImageView *showImageView = \
        [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"長圖.jpg"]];
    
    _showView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 50, 320, 100)];
    _showView.delegate = self;
    [_showView addSubview:showImageView];
    _showView.contentSize = showImageView.frame.size;
    [self.view addSubview:_showView];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint point = scrollView.contentOffset;
//    point.y = 0.f;
    scrollView.contentOffset = point;
}

@end

限制后效果:

//
//  RootViewController.m
//  BUG
//
//  Copyright (c) 2014年 Y.X. All rights reserved.
//

#import "RootViewController.h"

@interface RootViewController ()<UIScrollViewDelegate>

{
    UIScrollView    *_showView;
}

@end

@implementation RootViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImageView *showImageView = \
        [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"長圖.jpg"]];
    
    _showView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 50, 320, 100)];
    _showView.delegate = self;
    [_showView addSubview:showImageView];
    _showView.contentSize = showImageView.frame.size;
    [self.view addSubview:_showView];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint point = scrollView.contentOffset;
    
    // 限制y軸不動
    point.y = 0.f;
    
    scrollView.contentOffset = point;
}

@end

核心代碼:

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM