iOS之UIScrollView固定UIScrollView滑动的方向

转载自:http://www.cnblogs.com/YouXianMing/p/3806399.html


一般而言,我们通过这两个参数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
复制代码

核心代码:



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值