Search code examples
iosautolayoutpredicatevisual-format-language

How flexible size elements in visual format auto layout decide which predicate to use


In using auto layout programmatically with visual format, I am confused with how it makes decisions when given two predicates. For example, the following constraint:

"H:[myTextView(>=300,<=700)]"

So far, on every device I try, whether iPhone 5S, 6 or iPad, the width is always 300. In what case will the width be greater than 300? Also, iOS 7 is my deployment target for this app, using Swift.

Essentially, I want my view to fill most of the screen's width on an iPhone, but a little more than half on iPad.

My Solution

based on rdelmar's answer.

self.view.addConstraint(NSLayoutConstraint(
        item:self.infoTextView, attribute:.Width,
        relatedBy:.Equal, toItem:self.view,
        attribute:.Width, multiplier:0.23, constant:228))

Solution

  • You can't use >= and <= constraints that way, because when you evaluate that expression any value between the two will satisfy it, so the system usually just picks one or the other. In iOS 8, you can use size classes to give different constraints to different size screens.

    If you're programming for iOS 7, you need to either check which device you're on, and set the constraints accordingly, or make the width relative to the width of the view. I think you would have to use the other constraint method, constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:, though to do this. By using the multiplier and constant, you could make the view, say 300 wide on an iPhone, but 400 on an iPad (a multiplier of .223 and a constant of 228 would do that for a 320 point wide phone and 768 point wide iPad).