简体   繁体   English

带有水平分页的UIScrollView不会使子视图居中

[英]UIScrollView with horizontal paging` does not center subview

I am trying to use UIScrollView with paging enabled. 我试图在启用分页的情况下使用UIScrollView。 I am adding various UIView to UISCrollView as a subviews. 我将各种UIView作为子视图添加到UISCrollView。 I want those subview to be smaller than size of scroll view so I have modified my constrains accordingly. 我希望这些子视图小于滚动视图的大小,因此我相应地修改了约束。 Now when I actually swipe them left/ right then do not happened to be in center. 现在,当我实际向左/向右滑动它们时,就不会碰巧居中。 I was expecting it to show previous / next view peeking from sides with current page in center. 我期望它显示当前页面位于中心的侧面的上一个/下一个视图。

This is what it looks like 这就是它的样子 在此处输入图片说明

Below is my code scrollview implementation 下面是我的代码scrollview实现

    //
    //  ViewController.m
    //  Paging
    //

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UIScrollView *pagingScrollView;
@end

@implementation ViewController
- (UIScrollView *)pagingScrollView {
    if (!_pagingScrollView) {
        _pagingScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
        _pagingScrollView.translatesAutoresizingMaskIntoConstraints = NO;
        _pagingScrollView.backgroundColor = [UIColor orangeColor];
        _pagingScrollView.showsHorizontalScrollIndicator = NO;
        _pagingScrollView.showsVerticalScrollIndicator = NO;
        _pagingScrollView.contentInset = UIEdgeInsetsZero;
        _pagingScrollView.pagingEnabled = YES;
        _pagingScrollView.clipsToBounds = NO;
        _pagingScrollView.bounces = NO;
    }
    return _pagingScrollView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self scrollViewSetUp];

    NSDictionary *views = NSDictionaryOfVariableBindings(_pagingScrollView);

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_pagingScrollView]|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:views]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_pagingScrollView]|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:views]];
}

- (void)scrollViewSetUp {

    [self.view addSubview:self.pagingScrollView];

    UIView *lastView = nil;
    NSInteger arrayCount = 5;

    for(NSInteger index = 0; index < arrayCount; index++)
    {
        UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
        view.translatesAutoresizingMaskIntoConstraints = NO;
        view.backgroundColor = [UIColor yellowColor];

        [self.pagingScrollView addSubview:view];

        [self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
                                                                        attribute:NSLayoutAttributeTop
                                                                        relatedBy:NSLayoutRelationEqual
                                                                           toItem:self.pagingScrollView
                                                                        attribute:NSLayoutAttributeTop
                                                                       multiplier:1
                                                                         constant:40]];

        [self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
                                                                        attribute:NSLayoutAttributeHeight
                                                                        relatedBy:NSLayoutRelationEqual
                                                                           toItem:self.pagingScrollView
                                                                        attribute:NSLayoutAttributeHeight
                                                                       multiplier:0.80
                                                                         constant:0]];

        [self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
                                                                        attribute:NSLayoutAttributeWidth
                                                                        relatedBy:NSLayoutRelationEqual
                                                                           toItem:self.pagingScrollView
                                                                        attribute:NSLayoutAttributeWidth
                                                                       multiplier:0.80
                                                                         constant:0]];

        if (lastView == nil && index == 0){
            [self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[view(==_pagingScrollView)]"
                                                                                        options:0
                                                                                        metrics:nil
                                                                                          views:@{@"view":view, @"_pagingScrollView":_pagingScrollView}]];
        } else {
            [self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[lastView]-20-[view]"
                                                                                        options:0
                                                                                        metrics:nil
                                                                                          views:@{@"lastView":lastView, @"view":view, @"_pagingScrollView":_pagingScrollView}]];
        }

        if(index == arrayCount-1) {
            [self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[view]-20-|"
                                                                                        options:0
                                                                                        metrics:nil
                                                                                          views:@{@"view":view}]];
        }

        lastView = view;
    }
}
@end

Any pointers/comments/feedback highly appreciated. 任何指针/评论/反馈高度赞赏。 Thanks. 谢谢。

Is this you want? 这是你想要的吗? 在此处输入图片说明

//
//  ViewController.h
//  Test
//
//  Created by Lee on 7/8/16.
//  Copyright © 2016 Lee. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic, strong) UIScrollView *pagingScrollView;

@end



//
//  ViewController.m
//  Test
//
//  Created by Lee on 7/8/16.
//  Copyright © 2016 Lee. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UIScrollViewDelegate>
@property (nonatomic,strong)NSMutableArray *subviewsCenterArray;

@end

@implementation ViewController

- (UIScrollView *)pagingScrollView {
    if (!_pagingScrollView) {
        _pagingScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
        _pagingScrollView.translatesAutoresizingMaskIntoConstraints = NO;
        _pagingScrollView.backgroundColor = [UIColor orangeColor];
        _pagingScrollView.showsHorizontalScrollIndicator = NO;
        _pagingScrollView.showsVerticalScrollIndicator = NO;
        _pagingScrollView.contentInset = UIEdgeInsetsZero;
        _pagingScrollView.pagingEnabled = NO;
        _pagingScrollView.clipsToBounds = NO;
        _pagingScrollView.bounces = NO;
        _pagingScrollView.delegate = self;
    }
    return _pagingScrollView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self scrollViewSetUp];

    NSDictionary *views = NSDictionaryOfVariableBindings(_pagingScrollView);

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_pagingScrollView]|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:views]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_pagingScrollView]|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:views]];
}

- (void)scrollViewSetUp {

    [self.view addSubview:self.pagingScrollView];

    UIView *lastView = nil;
    NSInteger arrayCount = 5;
    _subviewsCenterArray = [NSMutableArray array];
    for(NSInteger index = 0; index < arrayCount; index++)
    {
        UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
        view.translatesAutoresizingMaskIntoConstraints = NO;
        view.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
        view.tag = 9999;
        view.layer.cornerRadius = 6;
        [self.pagingScrollView addSubview:view];

        [self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
                                                                          attribute:NSLayoutAttributeTop
                                                                          relatedBy:NSLayoutRelationEqual
                                                                             toItem:self.pagingScrollView
                                                                          attribute:NSLayoutAttributeTop
                                                                         multiplier:1
                                                                           constant:40]];

        [self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
                                                                          attribute:NSLayoutAttributeHeight
                                                                          relatedBy:NSLayoutRelationEqual
                                                                             toItem:self.pagingScrollView
                                                                          attribute:NSLayoutAttributeHeight
                                                                         multiplier:0.80
                                                                           constant:0]];

        [self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
                                                                          attribute:NSLayoutAttributeWidth
                                                                          relatedBy:NSLayoutRelationEqual
                                                                             toItem:self.pagingScrollView
                                                                          attribute:NSLayoutAttributeWidth
                                                                         multiplier:0.80
                                                                           constant:0]];

        if (lastView == nil && index == 0){
            [self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[view(==_pagingScrollView)]"
                                                                                          options:0
                                                                                          metrics:nil
                                                                                            views:@{@"view":view, @"_pagingScrollView":_pagingScrollView}]];
        } else {
            [self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[lastView]-20-[view]"
                                                                                          options:0
                                                                                          metrics:nil
                                                                                            views:@{@"lastView":lastView, @"view":view, @"_pagingScrollView":_pagingScrollView}]];
        }

        if(index == arrayCount-1) {
            [self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[view]-20-|"
                                                                                          options:0
                                                                                          metrics:nil
                                                                                            views:@{@"view":view}]];
        }

        [self.view layoutIfNeeded];




        lastView = view;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{

    [self changeTheCardStatus:scrollView];

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self changeTheCardStatus:scrollView];

}


-(void)changeTheCardStatus:(UIScrollView *)scrollView{

    for (UIView *view in scrollView.subviews) {
        if (view.tag == 9999) {
            [_subviewsCenterArray addObject:@(view.center.x)];
        }

    }



    CGFloat currentCenterOffsetX = scrollView.contentOffset.x + CGRectGetWidth(self.view.frame)/2.0;

    NSMutableArray *absoluteValueArray = [NSMutableArray array];
    NSMutableDictionary *absoluteValueDictionary = [NSMutableDictionary dictionary];
    for (int i  = 0; i < _subviewsCenterArray.count; i ++) {
        float subviewsCenterPointX = [_subviewsCenterArray[i] floatValue];
        double  absolute = fabs(subviewsCenterPointX - currentCenterOffsetX);
        [absoluteValueArray addObject:@(absolute)];
        [absoluteValueDictionary setValue:@(subviewsCenterPointX) forKey:[NSString stringWithFormat:@"%f",absolute]];
    }


    [absoluteValueArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {

        double a = [obj1 doubleValue];
        double b = [obj2 doubleValue];
        if (a>b) {
            return NSOrderedDescending;
        }
        else if (a<b){
            return NSOrderedAscending;
        }
        else{
            return NSOrderedSame;
        }

    }];


    double shortValue = [absoluteValueArray.firstObject doubleValue];
    double centerX = [[absoluteValueDictionary objectForKey:[NSString stringWithFormat:@"%f",shortValue]] doubleValue];
    [UIView animateWithDuration:0.25 animations:^{
        scrollView.contentOffset = CGPointMake(centerX - CGRectGetWidth(self.view.frame)/2.0, 0);

    }];

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Of course It's not. 当然不是。 The subview of pagingScrollView doesn't have a right width! pagesScrollView的子视图的宽度不正确! Also these subviews don's have correct horizontal margin. 这些子视图也没有正确的水平边距。

  1. First You should correct your setting width code, change the multiplier to 1 and constant to -40. 首先,您应该更正您的设置宽度代码,将乘数更改为1,将常数更改为-40。 Like this: 像这样:

     [self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.pagingScrollView attribute:NSLayoutAttributeWidth multiplier:1 constant:-40]]; 
  2. Then modify the subview margin, change -20 to -40, like this 然后修改子视图边距,将-20更改为-40

     [self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[lastView]-40-[view]" options:0 metrics:nil views:@{@"lastView":lastView, @"view":view, @"_pagingScrollView":_pagingScrollView}]]; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在UIScrollView的子视图中禁用水平滚动 - Disable horizontal scroll in a subview of UIScrollView UIScrollView中的UITableViewController与Horizo​​ntal Paging - UITableViewController inside UIScrollView with Horizontal Paging 将垂直UIScrollView与水平分页一起使用 - Using vertical UIScrollView with horizontal paging XCode - UIScrollView 分页不显示子视图(自动布局?) - XCode - UIScrollView Paging Not Showing SubView (Auto Layout?) UIScrollView和分页触摸事件未在子视图外部注册 - UIScrollView and paging touch events not registering outside subview UIScrollView 水平分页 like Mobile Safari tabs - UIScrollView horizontal paging like Mobile Safari tabs XCode自动布局无法与UIScrollView一起使用以进行水平分页 - XCode autolayout not working with UIScrollView for horizontal paging UITableViewCell内的UIScrollView在iPad上具有水平分页 - UIScrollView inside UITableViewCell With horizontal Paging on IPad 使用UIView作为子视图的水平分页的UIScrollView - UIScrollView with horizontal paging using UIView as Subviews UIScrollView子视图中的水平UISwipeGestureRecognizer? (UIScrollView只需要识别垂直滚动) - Horizontal UISwipeGestureRecognizer in subview of UIScrollView ? (UIScrollView only needs to recognize vertical scrolling)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM