簡體   English   中英

帶有水平分頁的UIScrollView不會使子視圖居中

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

我試圖在啟用分頁的情況下使用UIScrollView。 我將各種UIView作為子視圖添加到UISCrollView。 我希望這些子視圖小於滾動視圖的大小,因此我相應地修改了約束。 現在,當我實際向左/向右滑動它們時,就不會碰巧居中。 我期望它顯示當前頁面位於中心的側面的上一個/下一個視圖。

這就是它的樣子 在此處輸入圖片說明

下面是我的代碼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

任何指針/評論/反饋高度贊賞。 謝謝。

這是你想要的嗎? 在此處輸入圖片說明

//
//  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

當然不是。 pagesScrollView的子視圖的寬度不正確! 這些子視圖也沒有正確的水平邊距。

  1. 首先,您應該更正您的設置寬度代碼,將乘數更改為1,將常數更改為-40。 像這樣:

     [self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.pagingScrollView attribute:NSLayoutAttributeWidth multiplier:1 constant:-40]]; 
  2. 然后修改子視圖邊距,將-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM