Search code examples
uiscrollviewautolayoutios8.1

Horizontal autolayout constraint has some strange offset on UIScrollView/UIView


Last week I dived into auto layout. While coding my first app today, I faced a strange "bug" with UIScrollView and auto layout. I couldn't find any similar issue on here so I created a new topic.

Here is some example code:

    self.view.backgroundColor = UIColor.greenColor()

    let view = UIScrollView()
    view.setTranslatesAutoresizingMaskIntoConstraints(false)
    view.backgroundColor = UIColor.redColor()
    self.view.addSubview(view)

    let constraintH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[view]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": view])

    // two options fixing this bug: "H:|-0-[view]-0-|" or "H:|[view]|"
    // only horizontal constraint has this issue

    let constraintV = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[view]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": view])

    self.view.addConstraints(constraintH)
    self.view.addConstraints(constraintV)

First I thought the reason was iOS 8.3 Beta SDK, but issue is also present with iOS 8.1 SDK. So is it only me or is it some autolayout bug which I should report to Apple?

UPDATE: I modified the code from UIScrollView to UIView so you can see that this bug is also applied to a normal UIView as well.

enter image description here


Solution

  • The horizontal spaces is the Margin, which is introduced in iOS 8. You could try to run it on an iOS 7.1 simulator and there would be no margin.

    You were right, removing the dashes should fix it

    let constraintH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": view])  
    

    Also, if you are using a UIScrollView and AutoLayout you should read this https://developer.apple.com/library/ios/technotes/tn2154/_index.html