zoukankan      html  css  js  c++  java
  • 固定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

    核心代码:

  • 相关阅读:
    Flask学习笔记1:基础知识
    Git学习笔记3:下载指定项目的单个文件或文件夹
    Tensorflow学习笔记6:解决tensorflow训练过程中GPU未调用问题
    Python学习笔记32:UDP协议链接
    Python学习笔记31:图片URL批量转存到本地
    软件安装笔记3:tesseract-ocr for mac和homebrew
    软件安装笔记2:Aria2百度云加速下载器
    软件安装笔记1:破解安装SecureCRT for mac及解决中文乱码问题
    forward(转发)与redirect(重定向)的区别
    剑指Offer_编程题_丑数
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/3806399.html
Copyright © 2011-2022 走看看