Swift autolayout: update view's dimension

780 views Asked by At

I'm using PureLayout

I'm doing all the layout by code, by the way.

I have a UIScrollView that functions like Facebook's news feed. My scroll view has some subviews. Let's call 'em "cards".

I've set my constraints inside updateConstraints as such:

for (i, view) in enumerate(self.viewsForAutoLayout) {
    /** Set view dimension **/
    view.autoSetDimension(ALDimension.Width,  toSize: view.frame.width)
    view.autoSetDimension(ALDimension.Height, toSize: view.frame.height)

    /** Make 'em stack **/
    if i == 0 {
        view.autoPinEdgeToSuperviewEdge(
            ALEdge.Top,
            withInset: offset
        )
    } else {
        view.autoPinEdge(
            ALEdge.Top,
            toEdge: ALEdge.Bottom,
            ofView: self.viewsForAutoLayout[i - 1],
            withOffset: offset
        )
    }
}

self.setNeedsLayout()

And in layoutSubviews, this is where I resize the cards. Their respective height is being updated after an image is loaded from the internet (via NSURLConnection.sendAsynchronousRequest, fyi, but not related to this topic.) After that, I update my scrollView's height.

for (i, view) in enumerate(self.viewsForAutoLayout) {
    view.realignContent()
}

totalHeight += view.frame.size.height + offset

let size = CGSizeMake(AppConstants.ScreenSize.SCREEN_WIDTH, totalHeight)
self.scrollView.resizeContent(size) // extension

The problem is that they're not being aligned properly. It's like calling setNeedsLayout() (which eventually calls layoutSubviews() -- correct me if I've mistaken) that does not align the content at all. I've also made sure that setNeedsUpdateConstraints() is called as well.

I've tried calling this in layoutSubviews...

view.autoSetDimension(ALDimension.Height, toSize: view.frame.height)

...but I get some kind of warning:

Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this: (1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand,
refer to the documentation for the UIView property  
translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x1700918a0 V:[XXX.ContentBox:0x15fd63a80(928.986)]>",
    "<NSLayoutConstraint:0x170098bf0 V:[XXX.ContentBox:0x15fd63a80(1275.99)]>"
)

(ContentBox is my UIView for the card)

The cards look messed up. What should I do to align my cards properly?

I'd gladly answer side comments regarding the code if it helps understand the question. :) Suggestions on the side aren't bad either.

1

There are 1 answers

1
n.Drake On

Going by the warning you're seeing, it looks like you need to set view.translatesAutoresizingMaskIntoConstraints = false when you instantiate your card view.