简体   繁体   English

ios在Masonry中设置了uiscrollview的内容

[英]ios set contentsize of uiscrollview in Masonry

I use pure code (not storyboard or xib) to set size of all views, and I don't want to use hard code to set frame , so I use Masonry. 我使用纯代码(不是storyboard或xib)来设置所有视图的大小,我不想使用硬代码来设置框架,所以我使用了Masonry。

Now I have a scrollView and a set of views as subviews of the scrollview, the code is like this: 现在我有一个scrollView和一组视图作为scrollview的子视图,代码是这样的:

[self.scrollview addSubview:[self.imageviews objectAtIndex:0]];
[[self.imageviews objectAtIndex:0] mas_makeConstraints:^(MASConstraintMaker *make) {
    make.size.equalTo(self.scrollview);
    make.top.equalTo(@0);
    make.left.equalTo(@0);
}];
for (NSInteger i = 1; i < maxcnt ; i++) {
    [self.scrollview addSubview:[self.imageviews objectAtIndex:i]];
    UIImageView *previous = [self.imageviews objectAtIndex:i-1];
    [[self.imageviews objectAtIndex:i] mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(self.scrollview);
        make.top.equalTo(@0);
        make.left.equalTo(previous.mas_right);
    }];
}

But here comes the problem: 但问题出现了:

1) How I can use Masonry to set the contentsize of the scrollview? 1)我如何使用Masonry设置scrollview的contentsize The following code not works well because in rotate event, self.view.frame.size.width change. 以下代码不能正常工作,因为在rotate事件中, self.view.frame.size.width更改。

self.scrollview.contentSize = CGSizeMake(self.imageviews.count * self.view.frame.size.width, self.view.frame.size.height);

2) If I have to use the upper code to set, how to deal with rotate event so the contentsize is update well. 2)如果我必须使用上面的代码来设置,如何处理旋转事件以便contentsize更新。

You are almost there. 你快到了。 All you have to do is set a right constraint on the last image view. 您所要做的就是在最后一个图像视图上设置一个正确的约束。 By doing so you create a "connection" between the left side of the contentView and the right side. 通过这样做,您可以在contentView的左侧和右侧之间创建“连接”。 That way the UIScrollView "knows" how much space the subviews need and adjusts the contentSize accordingly. 这样,UIScrollView“知道”子视图需要多少空间,并相应地调整contentSize

There is no need to set the contentSize at all. 根本不需要设置contentSize Auto Layout handles this for you and it also works when rotating the device. 自动布局为您处理此问题,它也适用于旋转设备。

I wrote a blog post about this a little while ago. 不久前我写了一篇关于这个的博客文章 It uses SnapKit but that is basically just another name for "Masonry with Swift". 它使用SnapKit,但这基本上只是“与Swift的砌体”的另一个名称。 The syntax is pretty much the same. 语法几乎相同。 It describes a vertical scroll view but the idea is the same on a horizontal one. 它描述了一个垂直滚动视图,但在水平视图上的想法是相同的。

One more small thing: 还有一件小事:

Instead of doing this: 而不是这样做:

make.top.equalTo(self.scrollview.mas_top);

You can do this: 你可以这样做:

make.top.equalTo(self.scrollview);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM