通过UIKit坐标系来全面掌握iOS中的UIScrollView组件

2020-01-15 14:47:20丽君

UIKit,iOS,UIScrollView

修改bounds的原点坐标也相当于把整个坐标系向上拖动,因为View的frame没由变过,所以它相对于父View的位置没有变化过。

其实这就是UIScrollView滑动时所发生的事情。注意从一个用户的角度来看,他以为时这个View中的子View在移动,其实他们的在坐标系中位置(他们的frame)没有发生过变化。

打造你的UIScrollView
一个scroll view并不需要其中子View的坐标来使他们滚动。唯一要做的就是改变他的bounds属性。知道了这一点,实现一个简单的scroll view就没什么困难了。我们用一个gesture recognizer来识别用户的拖动操作,根据用户拖动的偏移量来改变bounds的原点:

复制代码
// CustomScrollView.h 
@import UIKit; 
  
@interface CustomScrollView : UIView 
  
@property (nonatomic) CGSize contentSize; 
  
@end 
复制代码   
// CustomScrollView.m 
#import "CustomScrollView.h" 
  
@implementation CustomScrollView 
  
- (id)initWithFrame:(CGRect)frame 

    self = [super initWithFrame:frame]; 
    if (self == nil) { 
        return nil; 
    } 
    UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] 
        initWithTarget:self action:@selector(handlePanGesture:)]; 
    [self addGestureRecognizer:gestureRecognizer]; 
    return self; 

  
- (void)handlePanGesture:(UIPanGestureRecognizer *)gestureRecognizer 

    CGPoint translation = [gestureRecognizer translationInView:self]; 
    CGRect bounds = self.bounds; 
  
    // Translate the view's bounds, but do not permit values that would violate contentSize 
    CGFloat newBoundsOriginX = bounds.origin.x - translation.x; 
    CGFloat minBoundsOriginX = 0.0; 
    CGFloat maxBoundsOriginX = self.contentSize.width - bounds.size.width;