I've got a view (non-autolayout) with autoresizingMask=UIViewAutoresizingFlexibleWidth
and translatesAutoresizingMasksIntoConstraints=YES
.
It is added to a superview with a width of 320, so it also is 320 width. On rotation to landscape it becomes 568 width. I’d like to limit width to 400 on rotation to landscape. My approach is when the orientation changes, set the view’s frame to 400 width if the superview is > 400.
- (void)orientationChanged:(NSNotification*)notification {
if (self.superview) {
float superviewWidth = self.superview.bounds.size.width;
if (superviewWidth > 400.0) {
CGRect oldFrame = self.frame;
self.frame = CGRectMake((superviewWidth - 400.0)/2.0, oldFrame.origin.y, 400.0, oldFrame.size.height);
}
}
}
My questions are, is it safe to change the view's frame
Generally when constraints are involved, resizing and animations are performed through them, not frames. Does that apply here as well? I'm concerned about any possible side effect to the size, like what can happen when frames instead of constraints are animated in pure autolayout.
If the view is configured with constraint-based layout, you shouldn't adjust the frames manually because it will get changed at the next layout pass. You can easily accomplish this by setting a maximum width constraint on the view.
If it's not configured with constraint-based layout, your current solution will work, although it's bad practice for a view to modify its own frame (a view's frame should be modified by its superview or its view controller).