So I decided to add a subview to my parent view, I created a new view and controller, and at runtime I initialize the subview's viewcontroller using initwithnibname to instantiate the view with the nib file. Then I simply make the call to addsubview and the view appears as expected and the subviewcontroller is properly handling all events in that subview... and stuff in the parent view continue to go to the parentview controller.
So, all is well and right with the world....
That is until I change orientation, when I change orientation, the subview does properly rotate itself in terms of its facing landscape or portrait, but it does not change its absolute location in the parent view... it continues to appear at the absolute coordinates it had for the other orientation, and does not adjust as one would expect.
I tried adding the various orientation change events to the subviewcontroller willanimate.. didrotate... but they never get called as the events only seem to go to the parentviewcontroller and do not get passed into subviewcontrollers.
This subview is using constraints, so the nice little autoadjust bars in IB are not there to try to solve this... so how the heck to I set this up so that when the orientation changes, the subviews actual location in the parent view should/must change as well?
Related
I am going to use it by adding a child VC. (Coding with code)
ChildVC is using autolayout (snapkit).
At initialization, viewDidLayoutSubviews is called twice.
At the first call, the childVC.View is set to full screen Frame.
In the second call, it is set according to the autolayout setting.
I found out that if the child VC's Frame is not set, it is set to full screen.
(Resize View From NIB)
I want to know how to turn off Resize View From NIB programmatically.
The problem is, I want to know why viewDidLayoutSubviews is called twice.
I'm curious as to why the childVC.View size changes when the second call is made.
I want to know one more thing. Isn't this usually used when setting subView's witdh and Height?
someView.snp.makeConstraints { make in
make.top.left.right.equalToSuperview()
make.width.equalTo(view.bounds.width)
make.height.equalTo(view.bounds.height * 0.58)
}
Based on VC.View bounds ratio?
I have a custom view (1) in the storyboard, and in that view's initialization it creates another view (2) and adds it as a subview. View 2 has implemented touchesBegan, touchesMoved, etc. The view controller has implemented touchesEnded. When I run it and do touches, only the view controller's touchesEnded is called. I don't know why view 2 isn't picking up the touches.
It appears view 2 is loaded properly because the custom background shows up.
I have tried explicitly setting userInteractionEnabled.
Now, get this. If I restart the iOS simulator, and run it, it works fine! But not if I run it a second time. And it never works when I run it on an actual ipad.
I don't expect anyone to magically know what the problem is, but any tips on how to debug this would be much appreciated!
Edit: initialization code for view 1...
self.myView2 = [[View2 alloc] initWithFrame:self.bounds];
[self addSubview:self.myView2];
For touch to happen, there are 4 conditions :
View should be userInterctionenabled.
Parent view should be userInteractionenabled
View should be in frames of parent view
View should not be hidden.
Check if all things are fine or not
I would also check to make sure that the frame of the parent view is large enough to hold the subview. The subview might be displayed but its touch area is being constrained by the frame of the parent view.
Of course, this situation would only happen if you set setClipsToBounds to FALSE in the parent view.
View 2 might be bigger than view (1)
It turns out that the "Autoresize Subviews" checkmark was the culprit. I designed my storyboard in portrait and was testing it in landscape. It seems that in landscape mode, the parent view was disappearing due to the rotation, but somehow the child view remained, giving the appearance that all was well.
When I unchecked "Autoresize Subviews" in the parent view, it worked.
Why rotation would make the parent view disappear is beyond me (I tested without a child view and that's what happened). And why the child view would be able to remain without the parent is also beyond me. If anyone can shine some light on this I would be happy to learn something. But right now I'm just happy that I didn't have to shoot myself.
This is in continuation to the problem I had here(which is still unresolved): link
But this may help understand what is the problem.
I created just a simple test project ('Empty Application') and added a view controller with a XIB file (check box: 'With XIB file for user interface' selected). Code looks like this:
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"didLoad: %#",NSStringFromCGRect(self.view.bounds));
// Do any additional setup after loading the view from its nib.
}
-(void) viewDidAppear:(BOOL)animated
{
NSLog(#"didAppear: %#",NSStringFromCGRect(self.view.bounds));
}
This is the output:
2013-07-26 17:05:28.502 testtest[5926:c07] didLoad: {{0, 0}, {320, 548}}
2013-07-26 17:05:28.506 testtest[5926:c07] didAppear: {{0, 0}, {320, 460}}
How come they are different?
(ps. I am testing on 6.1 simulator)
When the viewDidLoad method is called, your view controller has only just been loaded from your storyboard or XIB, and so the view dimensions are equal to those that you have in the XIB (those looks like iPhone 5 height dimensions).
Later, when viewDidAppear: is called, the view has already appeared on the screen, so it has been resized appropriately to actually fit on the screen, so its dimensions may be different to those in your storyboard, and consequently different to those that are set when the view is loaded.
In your case, it looks like your storyboard or XIB file is set to iPhone 5 screen size (548 = 1136/2 - status bar), and you are testing in a pre-iPhone 5 simulator or device with a 480x320 point screen, so the view gets resized down to 460 points high to fit on the screen.
This could have perfect sense.
ViewDidLoad is called lazily when first access of controller.view, so by that time the frame is not set yet. This means that you can not rely on the frame/bounds sizes at this point because it will only contain a default value (although in many cases it will be correct).
In ViewDidAppear, the frame is usually set, although if your parent controller is setting any animation you could also have a temporal frame state instead of the final one, but it is not usual as by convention this method is called when the view is already displayed.
For example, if you are loading the view from an IB file, the frame you will get in the viewDidLoad is the one you have in the IB file, but maybe the final size for your view is smaller/bigger, and then you will get another one in your viewDidAppear.
Instead of that, you should create all your elements resizable (use Spring&Struts, AutoLayout or any other similar alternative) so they will be properly displayed when the frame is set.
When a ViewController presents its view, it normally shrinks that
view so that its frame does not overlap the device’s status bar.
So when you NSLog in viewDidLoad, the View i not yet loaded so ViewController has not shrinked the frame yet but in viewDidAppear , it has done the resizing.
There is a property in UIViewController
wantsFullScreenLayout
Setting this property to YES causes the view controller to size its
view so that it fills the entire screen, including the area under the
status bar. (Of course, for this to happen, the window hosting the
view controller must itself be sized to fill the entire screen,
including the area underneath the status bar.) You would typically set
this property to YES in cases where you have a translucent status bar
and want your view’s content to be visible behind that view.
As far as i know, ViewDidLoad will set the bounds for your application as defined, in the RootViewController/XIB-file for root view, or maybe the AppDelegate.
If you define the applications bounds there (not sure in which one of these), ViewDidLoad functions in the entire app, will initially, set the height according to that.
Once the View is loaded, and ready to 'appear', actual bounds may be requested.
Hence it is advised to request bounds/sizes in the ViewWillAppear/ViewDidAppear methods.
-viewDidLoad is called the first time viewController.view is called. It is called before the view is returned. This has a very important implication. In order for the view to be shown or sized, it needs to be added to the window or some other view.
How does this happen? It looks something like [window addSubview:viewController.view].
So, the fully loaded view is needed before it can be placed into the view hierarchy. This places limitations on self.view when used within -viewDidLoad.
self.view.superview and self.view.window will always be nil.
self.view is not yet sized to fit into self.view.superview.
With this understanding, you can see how self.view cannot know it's final size when -viewDidLoad is called.
UPDATE
If you need to apply a custom layout to a view's subviews, you may want to consider subclassing UIView and using -[UIView layoutSubviews].
Barring that, are you having trouble with -viewWillAppear: instead of -viewDidAppear:? -viewWillAppear: is called before the view is displayed, so you won't have odd visual effects when you resize the view.
I am implementing an application which is locked to landscape only, containing a UIScrollView (the super view to add sub-views) and a UIPageControl.
When I trying to add a sub-view in viewDidLoad, calculating its frame by referencing its super view's frame, it is always portrait.
But the sub-view added later (say in the scrollViewDidScroll, when user swipes to next page) is landscape.
I set a break point and found that the super view's size is 768*969 in viewDidLoad and 1024 * 713 later.
I suspect it is because the app doesn't know about the orientation at all when viewDidLoad thus everything is default to portrait layout. Am I right?
If so, when will the app know about the orientation for the first time?
Thanks.
The workaround I found was to reparent the scroll view under an intermediate view
VC
view
view (intermediate view)
scrollview
Then the frame of the scroll view was correct in viewdidload (previously without the intermediate view, the frame was in portrait right up until viewdidappear!)
I have a custom view that's not getting layoutSubview messages during animation.
I have a view that fills the screen. It has a custom subview at the bottom of the screen that correctly resizes in Interface Builder if I change the height of the nav bar. layoutSubviews is called when the view is created, but never again. My subviews are correctly laid out. If I toggle the in-call status bar off, the subview's layoutSubviews is not called at all, even though the main view does animate its resize.
Under what circumstances is layoutSubviews actually called?
I have autoresizesSubviews set to NO for my custom view. And in Interface Builder I have the top and bottom struts and the vertical arrow set.
Another part of the puzzle is that the window must be made key:
[window makeKeyAndVisible];
of else the subviews are not automatically resized.
I had a similar question, but wasn't satisfied with the answer (or any I could find on the net), so I tried it in practice and here is what I got:
init does not cause layoutSubviews to
be called (duh)
addSubview: causes
layoutSubviews to be called on the
view being added, the view it’s being
added to (target view), and all the
subviews of the target
view setFrame
intelligently calls layoutSubviews on
the view having its frame set only
if the size parameter of the frame is
different
scrolling a UIScrollView
causes layoutSubviews to be called on
the scrollView, and its superview
rotating a device only calls
layoutSubview on the parent view (the
responding viewControllers primary
view)
Resizing a view will call layoutSubviews on its superview (Important: views with an intrinsic content size will re-size if the content that determines their size changes; for example, updating the text on a UILabel will cause the intrinsic content size to be updated and thus call layoutSubviews on its superview)
My results - http://blog.logichigh.com/2011/03/16/when-does-layoutsubviews-get-called/
Building on the previous answer by #BadPirate, I experimented a bit further and came up with some clarifications/corrections. I found that layoutSubviews: will be called on a view if and only if:
Its own bounds (not frame) changed.
The bounds of one of its direct subviews changed.
A subview is added to the view or removed from the view.
Some relevant details:
The bounds are considered changed only if the new value is different, including a different origin. Note specifically that is why layoutSubviews: is called whenever a UIScrollView scrolls, as it performs the scrolling by changing its bounds' origin.
Changing the frame will only change the bounds if the size has changed, as this is the only thing propagated to the bounds property.
A change in bounds of a view that is not yet in a view hierarchy will result in a call to layoutSubviews: when the view is eventually added to a view hierarchy.
And just for completeness: these triggers do not directly call layoutSubviews, but rather call setNeedsLayout, which sets/raises a flag. Each iteration of the run loop, for all views in the view hierarchy, this flag is checked. For each view where the flag is found raised, layoutSubviews: is called on it and the flag is reset. Views higher up the hierarchy will be checked/called first.
https://developer.apple.com/library/prerelease/tvos/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/CreatingViews/CreatingViews.html#//apple_ref/doc/uid/TP40009503-CH5-SW1
Layout changes can occur whenever any of the following events happens
in a view:
a. The size of a view’s bounds rectangle changes.
b. An interface orientation change occurs, which usually triggers a change in the root view’s bounds rectangle.
c. The set of Core Animation sublayers associated with the view’s layer changes and requires layout.
d. Your application forces layout to occur by calling the setNeedsLayout or layoutIfNeeded method of a view.
e. Your application forces layout by calling the setNeedsLayout method of the view’s underlying layer object.
Some of the points in BadPirate's answer are only partially true:
For addSubView point
addSubview causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target.
It depends on the view's (target view) autoresize mask. If it has autoresize mask ON, layoutSubview will be called on each addSubview. If it has no autoresize mask then layoutSubview will be called only when the view's (target View) frame size changes.
Example: if you created UIView programmatically (it has no autoresize mask by default), LayoutSubview will be called only when UIView frame changes not on every addSubview.
It is through this technique that the performance of the application also increases.
For the device rotation point
Rotating a device only calls layoutSubview on the parent view (the responding viewController's primary view)
This can be true only when your VC is in the VC hierarchy (root at window.rootViewController), well this is most common case. In iOS 5, if you create a VC, but it is not added into any another VC, then this VC would not get any noticed when device rotate. Therefore its view would not get noticed by calling layoutSubviews.
I tracked the solution down to Interface Builder's insistence that springs cannot be changed on a view that has the simulated screen elements turned on (status bar, etc.). Since the springs were off for the main view, that view could not change size and hence was scrolled down in its entirety when the in-call bar appeared.
Turning the simulated features off, then resizing the view and setting the springs correctly caused the animation to occur and my method to be called.
An extra problem in debugging this is that the simulator quits the app when the in-call status is toggled via the menu. Quit app = no debugger.
calling
[self.view setNeedsLayout];
in viewController makes it to call viewDidLayoutSubviews
have you looked at layoutIfNeeded?
The documentation snippet is below. Does the animation work if you call this method explicitly during the animation?
layoutIfNeeded
Lays out the subviews if needed.
- (void)layoutIfNeeded
Discussion
Use this method to force the layout of subviews before drawing.
Availability
Available in iPhone OS 2.0 and later.
When migrating an OpenGL app from SDK 3 to 4, layoutSubviews was not called anymore. After a lot of trial and error I finally opened MainWindow.xib, selected the Window object, in the inspector chose Window Attributes tab (leftmost) and checked "Visible at launch". It seems that in SDK 3 it still used to cause a layoutSubViews call, but not in 4.
6 hours of frustration put to an end.