即使添加子视图也无法使用锚添加约束

时间:2018-08-16 11:00:02

标签: ios nslayoutconstraint

我是iOS的新手。这是导致错误的代码。

FSImageView *imageView = [_imageViews objectAtIndex:(NSUInteger) page];
if ((NSNull *) imageView == [NSNull null]) {
        imageView = [self dequeueImageView];
        if (imageView != nil) {
            [_imageViews exchangeObjectAtIndex:(NSUInteger) imageView.tag withObjectAtIndex:(NSUInteger) page];
            imageView = [_imageViews objectAtIndex:(NSUInteger) page];
        }
    }

    if (imageView == nil || (NSNull *) imageView == [NSNull null]) {
        imageView = [[FSImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, _scrollView.bounds.size.width, _scrollView.bounds.size.height)];
        UIColor *backgroundColor = barsHidden ? _backgroundColorHidden : _backgroundColorVisible;
        [imageView changeBackgroundColor:backgroundColor];
        [_imageViews replaceObjectAtIndex:(NSUInteger) page withObject:imageView];
    }

    imageView.useScaleFactor = self.useScaleFactor;
    imageView.image = _imageSource[page];
if (imageView.superview == nil) {
        [_scrollView addSubview:imageView];

        if (@available(iOS 11.0, *)) {
            [imageView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor
                                                constant:0.0].active = YES;
            [imageView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor
                                                   constant:0.0].active = YES;
        } else {
            // Fallback on earlier versions
        }
    }

该异常发生在Anchor的东西上。它说..

由于未捕获的异常“ NSGenericException”而终止应用程序,原因:“无法激活具有锚点的约束,并且它们没有共同的祖先。约束或其锚点是否引用了不同视图层次结构中的项目?那是非法的。'

1 个答案:

答案 0 :(得分:0)

此时查看您的代码

[imageView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor
                                            constant:0.0].active = YES;
[imageView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor
                                               constant:0.0].active = YES;

您正在尝试针对SuperView(即您的scrollView)的superView(即您的self.view)激活约束那是非法的

  

您的结构类似于UIView-> ScrollView-> imageView。并且您正在从UIView设置锚,则应尝试相对于ScrollView设置锚。

编辑

您应该尝试以下操作:

[imageView.topAnchor constraintEqualToAnchor:_scrollView.topAnchor
                                                constant:0.0].active = YES;
[imageView.bottomAnchor constraintEqualToAnchor:_scrollView.bottomAnchor
                                                   constant:0.0].active = YES;

还为 .leftAnchor和.rightAnchor设置。

编辑

[_scrolLView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor
                                                constant:0.0].active = YES;
[_scrolLView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor
                                                   constant:0.0].active = YES;

还为 .leftAnchor和.rightAnchor设置。

尝试并分享结果。

希望有帮助。