Reputation: 1858
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))
Upvotes: 0
Views: 487
Reputation: 385960
Your format specifies two constraints:
myTextView.width >= 300
and
myTextView.width <= 700
The constraint solver is allowed to choose any solution that meets both constraints. This means that it can pick 300 every time, as long as picking 300 doesn't break any other constraints.
Auto layout cannot read your mind. You need to be explicit about what you want. What is “most of the screen's width”, exactly? What is “a little more than half”, exactly?
If your deployment target is iOS 8, you can use size classes to define different constraints for iPhones and iPads. You should watch the WWDC 2014 “What's New in Cocoa Touch” video to learn about this.
If your deployment target is iOS 7 or earlier, you can either modify your constraints programmatically, or you can have one storyboard for iPhones and another for iPads.
Upvotes: 1
Reputation: 104082
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).
Upvotes: 1