【问题标题】:UIScrollView as subview of UIView does not work with autolayoutUIScrollView 作为 UIView 的子视图不适用于自动布局
【发布时间】:2016-03-24 12:11:52
【问题描述】:

我创建了一个 customView (UIView),其中包含一个 UIScrollView 作为其子视图,并且 我放在 scrollView 上的对象没有显示。为了测试它,我在 scrollView 中添加了一个 UIView,但它都没有显示(参见下面的代码示例)。由于我想放在 scrollView 上的内容是动态的,我想通过使用 AutoLayout 来解决这个问题。我尝试了不同的方法并按照在线说明进行操作,但都没有奏效,所有类似的问题都是在 UIViewController 内部创建的 UIScrollView。

这是我的代码,我正在使用 Masonry:

@interface CustomView : UIView

@end

@implementation CustomView

- (instancetype)init {
    if (self = [super init]) {

        self.scrollView = [[UIScrollView alloc]init];
        self.scrollView.backgroundColor = [UIColor redColor];
        [self addSubview:self.scrollView];
        [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];

    //Here I add someView to the scrollView, and when I create an instance of the scrollView, the someView does not show.

    self.someView = [[UIView alloc]init];
    self.someView.backgroundColor = [UIColor blackColor];
    [self.scrollView addSubview:self.someView];        
    [self.someView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.size.equalTo(CGSizeMake(40, 40));
    }];
}
return self;
}

这是我创建 CustomView 实例的方法

CustomView *customView = [[CustomView alloc]init];
[self.view addSubview: customView];
[customView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(64.0);
    make.height.equalTo(40.0);
    make.leading.trailing.equalTo(0);
}];

是否有什么我错过或做错导致 someView 无法显示?

感谢您的帮助。

【问题讨论】:

  • 您的滚动视图是否按预期显示?否则请检查在为滚动视图和某些视图设置约束时是否获得正确的框架,控制台中是否显示任何自动布局错误?
  • 感谢@pyro 提醒我放置断点并检查滚动视图,我累了,视图已正确创建。一位同事通过移除 UIView 的冗余层并正确使用 AutoLayout 帮助我解决了这个 bug。

标签: ios autolayout scrollview masonry


【解决方案1】:

我通过以下方式解决了这个问题: 1). 直接使用 scrollView 而不是作为 UIView 中的子视图(我的 customView)。 2)确保添加scrollView的右下约束。

【讨论】:

    猜你喜欢
    • 2015-11-30
    • 2013-01-04
    • 1970-01-01
    • 2014-11-17
    • 2017-04-28
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多