Rectangle 27 4

In short, when -view is called the first time, -viewDidLoad is called. Even if the very first thing a view controller does to a view is set the frame, it still needs to access the view.

UIViewController *controller = [MyViewController myViewController];

// -viewDidLoad has not been called (if +myViewController doesn't call -view.)

UIView *view = [controller view];

// -viewDidLoad has been called.

view.frame = [UIApplication sharedApplication].delegate.window.bounds;

Even if you use controller.view.frame the same logical sequence happens. -viewDidLoad will always be a called with a freshly deserialized view that has not been embedded into the view hierarchy.

It case it wasn't clear earlier, I was pointing out why the bounds of view are not set correctly in -viewDidLoad. It is only after -viewDidLoad does the view controller's view get added to the view hierarchy. This is when the final frame of the view is set.

If you must have the frame be the right dimensions, you can use IB to set the dimensions that you know you'll need or (if you don't use IB) set the frame in -loadView. This approach is flawed because it statically sets the size of the frame to a value that may be changed after -viewDidLoad is called (things like the in-call status bar).

You need to split the adding subviews from positioning and sizing subviews.

If you are loading from a Storyboard or a Nib, then you are correct, additional views needed should be added in -viewDidLoad. If you're loading programmatically, then all subviews are added in -loadView.

The second task is positioning and sizing subviews. The preferred method is to use UIView.autoresizingMask, but for more precise layout, KVO view.bounds and adjust your custom subviews when view controller's view changes its size.

Even if I request [controller view] immediately after creating the controller, it makes no difference. First I create the controller. Second, I (for now) just assign the controller's view to a variable - just to reference it. Then I change the frame. For any demand-loaded cycles this works - for any triggered in the view didLoad of the mainVC, it does not. If I have misunderstood, and you are referring to my mainVC in your example, then how am I meant to load some other view controllers at launch, and add their views?

Sorry, maybe I wasn't clear-viewDidLoad will always be called before the final bounds or frame is set. Always. There is nothing you can do about it.

Where should I add subviews? In viewWillAppear? Seems like I would be doing a lot of unnecessary reprocessing.

The short answer is split add subviews from positioning and sizing subviews.

@Jeffery Thomas: I have a similar question here, I think your feedback would be useful:

ios - Bounds and Frame size in viewDidLoad - Stack Overflow

ios cocoa-touch uiview uiviewcontroller bounds
Rectangle 27 6

Never rely on frame and bound values in viewDidLoad/viewWillAppear. Usually the most precise location to listen to size changes is viewDidLayout, where you can keep track of the last seen size, and do your logic if the size changed.

viewDidAppear is precise, but is called after the view has already animated in, so you will see an ugly jump. viewWillLayout/viewDidLayout is usually the most precise one, as I mentioned before.

Maybe I wasn't clear enough. I don't want to change anything! I have a xib with 596W/400H. I have my labels/text/buttons all set up in the XIB. When the VC loads in 7.1 it is 540W/620H. I cannot see the right side of my VC which has buttons in it! This works perfectly in iOS8, but NO in iOS7.1.

This was not clear to me from the question. Please post how you load your xib content.

updated with code requested and also with NSLog output

@Jerry, are fW and fH correct values in both cases?

NO - that is the issue - - looking at the log, you can see in iOS7 it changes to 540/620 wheres in iOS8 it stays put at 596/400 (which is my XIB size).

ios - frame size changes between viewdidload and viewwillappear in iOS...

ios objective-c
Rectangle 27 2

Figured out what I was doing wrong: I was looking at the frame size in the viewDidLoad method. It's not always valid at that point, for some reason.

The correct place to check the frame size is viewDidAppear; it seems to be valid there. Admittedly, though, I haven't checked this in every single corner case, so YMMV.

ipad - ios: Get size of parent popover from child viewController? - St...

ios ipad viewcontroller popover
Rectangle 27 2

I had similar problems performing calculations with frame sizes in viewDidLoad and awakeFromNib. Everything worked dandily in swift 2.3 and then things disappeared in swift 3

You can move the code to viewDidAppear, or call self.view.layoutIfNeeded() beforehand

ios - Swift 3 add a custom border to one of the edges of UIView - Stac...

ios uiview swift3
Rectangle 27 5

Auto layout doesn't give you the "right" frame sizes until a layout pass has happened. viewDidLoad is too early, and off the top of my head willAppear might be too. viewDidLayoutSubviews is the right place.

ios - Autolayout is not updating frames instantly in iOS8-Xcode6 - Sta...

ios ios8 autolayout xcode6
Rectangle 27 2

On this VC I programatically adjust the frame of a UILabel which is inside the scroll view. This is done on viewDidLoad.

It is generally a bad idea to modify view frames in viewDidLoad, because the system's layout phase (during which layoutSubviews messages are sent) hasn't happened yet. In viewDidLoad, your view's frame hasn't been adjusted for the current device's screen size and interface orientation yet.

Second, you said that you're using autolayout. The autolayout system sets the frames of views during the layout phase. The layout phase can be triggered by many different events, including (as you've discovered) the appearance and disappearance of views.

In order to make your adjustment to the label's frame stick, you need to modify the constraints that control the label's frame. One way to do this is to create an outlet of type NSLayoutConstraint on your view controller for each constraint that you need to modify, and connect these outlets to the constraints in your xib. Then in your view controller's viewWillLayoutSubviews, you can modify the constant property of each constraint as necessary. (Ironically, constant is the only modifiable property of an NSLayoutConstraint.)

Although this didn't really solve my issues, Rob's observations are spot on and through these findings I solved my problems. I won't share my solution as it is extremely outside of the ordinary, but in a nutshell I ended up creating the controls programmatically and not using autoLayout.

ios - layoutSubview resetting properties of UILabel - Stack Overflow

ios objective-c uiscrollview layoutsubviews
Rectangle 27 17

I found that adding the following 2 lines of code in viewDidLoad of SecondViewController (where you want to hide TabBar but show the tool bar) fixes the problem.

self.extendedLayoutIncludesOpaqueBars = YES;
self.edgesForExtendedLayout = UIRectEdgeBottom;

My viewDidLoad of SecondViewController is as follows:

- (void)viewDidLoad {
    [super viewDidLoad];
    // These 2 lines made the difference
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.edgesForExtendedLayout = UIRectEdgeBottom;

    // The usual configuration
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationController.navigationBar.translucent = NO;

    self.navigationController.toolbarHidden = NO;
    self.navigationController.toolbar.barStyle = UIBarStyleBlack;
    self.navigationController.toolbar.translucent = NO;

But you need to fix the frame of the view manually as this causes the size to be (320x504). Which means it extends even behind the tool bar. If this is not a concern for you then this solution should work.

Thanks, this is very helpful - making the bar opaque does seem to work around the "dead zone" bug

iphone - On iOS 7, pushing a controller with a toolbar leaves a gap of...

ios iphone objective-c ios7 uinavigationcontroller
Rectangle 27 13

I want to mention something that caught me first when I was trying to adapt a SpriteKit-based app to avoid the round edges and "notch" of the new iPhone X, as suggested by the latest Human Interface Guidelines: The new property safeAreLayoutGuide of UIView needs to be queried after the view has been added to the hierarchy (for example, on -viewDidAppear:) in order to report a meaningful layout frame (otherwise, it just returns the full screen size).

The layout guide representing the portion of your view that is unobscured by bars and other content. When the view is visible onscreen, this guide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. (In tvOS, the safe area reflects the area not covered the screen's bezel.) If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide edges are equal to the edges of the view.

{{0, 0}, {375, 812}}
{{0, 44}, {375, 734}}

It took me for a while to figure out...

Same here. I always jump at the available properties of a type, guided by their names only, without fully reading the docs...

I was this close to posting a question on SO before figuring it out (typically, it's the other way around...)

ios - Safe Area of Xcode 9 - Stack Overflow

ios swift ios11 xcode9 safearealayoutguide
Rectangle 27 1

I had a similar problem with a UITableView in a sub-view on my window. I solved it by setting the size of the frame of my UINavigationController in viewDidLoad. For some reason the subview was not constraining itself to the size of the view specified in Interface Builder. Here is what worked for me:

- (void)viewDidLoad {
    [super viewDidLoad];

    UINavigationController *navigationController = [[UINavigationController alloc] init];
    RootViewController *rootController = [[[RootViewController alloc] initWithStyle:UITableViewStylePlain] autorelease];
    rootController.managedObjectContext = self.managedObjectContext;
    [navigationController.navigationBar setBarStyle:UIBarStyleBlackOpaque];
    [navigationController pushViewController:rootController animated:YES];
    [navigationController.view setFrame:CGRectMake(0, 0, 500, self.view.frame.size.height)];
    [self.leftView addSubview:[navigationController view]];

UITableView too wide for portrait iPad - Stack Overflow

ipad uitableview
Rectangle 27 2

It work for me, "For some reason, viewDidLoad is too early in the life cycle to obtain the scroll view's adjusted frame on iOS 8, but again it works on iOS 7. viewWillAppear is also too early, as well as viewWillLayoutSubviews.

To solve the problem, I just moved the code where I need to use the scroll view's frame size to viewDidLayoutSubviews which does finally obtain the correct size it will be when it appears." UIScrollView frame is a different size on iOS 8 vs iOS 7

ios - UIScrollview works in iOS8, not in iOS7 - Stack Overflow

ios uiscrollview
Rectangle 27 1

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.

        self.view.addSubview(makeLabel("my title",x: 0, y: 100, w: 320, h: 30))

    func makeLabel(title:String, x:CGFloat, y:CGFloat, w:CGFloat, h:CGFloat)->UILabel{
        var myLabel : UILabel = UILabel(frame: CGRectMake(x,y,w,h))
        myLabel.textAlignment = NSTextAlignment.Right

        // inser last char to right
        var titlePlus1char = "\(title)1"
        myLabel.text = titlePlus1char
        var titleSize:Int = count(titlePlus1char)-1

        myLabel.textColor = UIColor(red:1.0, green:1.0,blue:1.0,alpha:1.0)
        myLabel.backgroundColor = UIColor(red: 214/255, green: 167/255, blue: 0/255,alpha:1.0)

        // create myMutable String
        var myMutableString = NSMutableAttributedString()

        // create myMutable font
        myMutableString = NSMutableAttributedString(string: titlePlus1char, attributes: [NSFontAttributeName:UIFont(name: "HelveticaNeue", size: 20)!])

        // set margin size
        myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue", size: 10)!, range: NSRange(location: titleSize,length: 1))

        // set last char to alpha 0
        myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red:1.0, green:1.0,blue:1.0,alpha:0), range: NSRange(location: titleSize,length: 1))

        myLabel.attributedText = myMutableString

        return myLabel

    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.


ios - Adding space/padding to a UILabel - Stack Overflow

ios uilabel padding
Rectangle 27 1

Alright I am going to take a stab at helping you. First the reason why it is not working is autolayout has position your views but you have a frame of size zero basically. To show you this go to the controller in question and have it clip its subviews and they will not show up during the transition. Now I probably would not change the frame to move it in since you just want to slide it in and you can probably get rid of some code. Here is what it looks like for me.

import UIKit

class ViewController: UIViewController,UIViewControllerTransitioningDelegate {

    var animator = Animator()

    override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.

    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

    @IBAction func presentModally(_ sender: Any) {
        self.performSegue(withIdentifier: "modal", sender: nil)

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "modal"{
           let dvc = segue.destination
            dvc.transitioningDelegate = self
            dvc.modalPresentationStyle = .overCurrentContext

    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        animator.transitioningMode = .Present // sabe que est em presenting mode
        return animator

    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        animator.transitioningMode = .Dismiss // Sabe que est em dismissing mode
        return animator


Delete the Custom Presentation Controller. I honestly don't see a need for it.

import UIKit

class Animator: NSObject,UIViewControllerAnimatedTransitioning {
    enum Status {
        case Present
        case Dismiss
    var transitioningMode: Status = .Present
    var presentDuration = 1.0
    var dismissDuration = 0.3

    // Tempo da animao
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        if (transitioningMode == .Present) {
            return presentDuration
        } else {
            return dismissDuration

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {

        // Get the set of relevant objects.
        let containerView = transitionContext.containerView

            let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
            let toVC = transitionContext.viewController(forKey:
            else {
                print("Returning animateTransition VC")

        let toView = transitionContext.view(forKey:
        let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)

        // Set up some variables for the animation.
        let containerFrame:     CGRect = containerView.frame
        let toViewFinalFrame:   CGRect = transitionContext.finalFrame(for: toVC)
        var fromViewFinalFrame: CGRect = transitionContext.finalFrame(for: fromVC)

        // Set up animation parameters.
        if (transitioningMode == .Present) {
            let anchor = toViewFinalFrame.origin
            toView?.layer.anchorPoint = anchor
            toView?.layer.position = anchor
            toView?.transform = CGAffineTransform(scaleX: 0, y: 1)
            //another posibility
            //toView?.transform = CGAffineTransform(translationX: -containerView.bounds.width, y: -containerView.bounds.height)
        } else {
            // Modify the frame of the dismissed view so it ends in
            // the lower-right corner of the container view.
            fromViewFinalFrame = CGRect(x: containerFrame.size.width,
                                        y: containerFrame.size.height,
                                        width: (toVC.view.frame.size.width),
                                        height: (toVC.view.frame.size.height))

        if (transitioningMode == .Present) {
            // Always add the "to" view to the container.
            // And it doesn't hurt to set its start frame.
           // toView?.frame = toViewStartFrame

        // Animate using the animator's own duration value.
        UIView.animate(withDuration: presentDuration, animations: {

            if (self.transitioningMode == .Present) {
                // Move the presented view into position.
                toView?.transform = .identity
            else {
                // Move the dismissed view offscreen.
                fromView?.frame = fromViewFinalFrame
        }) { (finished) in
            let success = !(transitionContext.transitionWasCancelled)
            // After a failed presentation or successful dismissal, remove the view.
            if ((self.transitioningMode == .Present && !success) || (self.transitioningMode == .Dismiss && success)) {

            // Notify UIKit that the transition has finished




I thought that is was required he custom presentation class if I'm the future I wanted to change the view controllers size. I'll try what you wrote and I'll feedback it soon. Thanks for helping :)

You could keep the custom presentation controller but I would return the exact size you want the frame to be and use translation or scale to move it in to place. Just my 2 cents. When I do animation and I am actually going to change the frames I generally take a snapshot and hid the original and unhide and remove the snapshot at the end. But I only animate the snapshot of the view or subview. That way I never really manipulate the frame of the real view. Hope this helps as well.

Nice tip. Have you seen the new animation on iOS 10.3 of the ? When you're creating a new email, the view controller comes from the bottom, but doesn't hit the top , it's like 90% of the size, the background view controller scales out a bit and you can see both of them. That's what I'm trying to create here ;)

ios - My subviews doesn't animate with the view controller - Stack Ove...

ios animation swift3 uimodalpresentationcustom
Rectangle 27 14

NSLog("frame=%@ transform=%@", NSStringFromCGRect(self.frame), NSStringFromCGAffineTransform(self.transform));

I'm willing to bet that transform is the identity (1,0,0,1,0,0) when frame size is 480x320, and a 90 rotation (0,1,-1,0,0,0 or 0,-1,1,0,0,0) when frame size is 320x480.

Well, viewDidLoad (and I think viewWillAppear) are called before the view is added to the view hierarchy. When it's added to the hierarchy, UIKit also sets the view transform, which is how rotation happens.

But why does that change the frame?

Well, the "frame" is relative to the parent view, which is the UIWindow. The window doesn't rotate; the view controller's view does. From the window's perspective, everything is effectively in portrait mode.

You probably want self.view.bounds.

Great explanation! This is the first time this actually made sense for me :)

iphone - self.view.frame changed size ifself unexpectedly in landscape...

iphone size frame landscape
Rectangle 27 0

I think it'll give you some clarification of whats going on here.

iphone - viewDidLoad and setting frame size in UIViewControllerContain...

iphone objective-c ios ipad uiviewcontroller
Rectangle 27 0

You need to add scrollview programatically with specific frame size. You have to add UIScrollViewDelegate in .h file. You have to enable scrollview for that you need to write following in viewDidLoad().


scrollview.frame = CGRectMake(x,y,width,height);
//---set the content size of the scroll view--- 

[scrollview setContentSize:CGSizeMake(height,width)];

In this way you can add your x,y,width and height values. I think this will help you.

ios - How to make a UITextField move up when keyboard is present - Sta...

ios iphone objective-c uitextfield uikeyboard
Rectangle 27 0

In viewDidLoad, the frame may not have adjusted to all of the things that affect its final size, such as rotation, other views, etc. It's generally best to only create and set up your objects here; you can inspect the finalized frame in viewWillLayoutSubviews.

viewWillLayoutSubviews is called every time the view rotates. Rotation is my next problem, and setting up the frame there causes it to jump, unlike the smooth autorotation that safari has.


ios - How do I get the size of a UIView from within the View Controlle...

ios objective-c uiview uiviewcontroller
Rectangle 27 0

There are no correct frames/sizes of views in viewDidLoad. You should ajust sizes in viewDidLayoutSubviews. Read more here:

If you are using auto layout, assign sufficient constraints to each of the views you just created to control the position and size of your views. Otherwise, implement the viewWillLayoutSubviews and viewDidLayoutSubviews methods to adjust the frames of the subviews in the view hierarchy. See Resizing the View Controllers Views.

ios - how to increase size of toolbar which has textview in it - Stack...

ios objective-c uitextview uitoolbar
Rectangle 27 0

View controllers should not have initWithFrame: methods. What I do in all of my code (I never use IB) is to let the default loadView do its own thing. I create and setup all subviews in viewDidLoad. At this point the view controller's frame has at least a sane value. All subviews can be created with their own sane frames based on the initial size of the view controller's view. With proper autoresizingMask values this may be all you need.

If you need more specific subview layout, put the appropriate layout code in the viewWillLayoutSubviews method. This will deal with any view controller view frame changes including rotation, in-call status bars, etc.

Isn't autolayout a function of IB? Then no. I've never used it. I do everything in code. IB makes no sense to me. I've been coding iOS apps for over 5 years and I have never felt the need for IB.

You can use autolayout without IB. Saves a lot of calculations.

Yes. As far as I know autolayout refers to the mechanism of calculating frames from constraints. IB is just a UI for it.

objective c - iOS - Where to initialize views - Stack Overflow

ios objective-c cocoa-touch
Rectangle 27 0

Use this:- In ViewDidLoad give frame size of youranotherviewcontroller likewise so that it covers only 30% Of the screen.after that :-

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
    UITouch *touch = [[event allTouches] anyObject]; 

    CGPoint startLocation = [touch locationInView:self.view];
    if([touch view]==yourFirstImageIcon)
        // alloc this youranotherviewcontroller in ViewDidLoad
        [self presentModalViewController:youranotherviewcontroller animated:Yes];
        //It will show your another View having five more icons like keyboard

iphone - Open a view (another xib) on button click in ipad application...

iphone ios ipad
Rectangle 27 0

It might be a layout issue. Setting clipToBounds to false would show the image even if its size is zero. Can you print the frame of your images?


I originally attempted setting corner radius and clipsToBounds in both viewDidLoad and viewDidAppear with no result. I attempted with viewDidLayoutSubviews to no avail as welll. When I enter the Debug View Hierarchy, I can see the frame for the UIImage within the UIImageView being drawn - just no image shown. It is also worth mentioning (I forgot in my original posting), that the project is still Swift 2.x and not updated to Swift 3.0 syntax.

printing the frame yields: (137.5, 24.0, 100.0, 100.0)

ios - clipsToBounds causes UIImage to not display in iOS10 & XCode 8 -...

ios uiimageview uiimage ios10 xcode8