简体   繁体   中英

UIView has zero width and height even though it's visible

I have created a subclass of UIView and called it MSMobileControlView . I added a UIView object to my Autolayout-enabled storyboard, and assigned it's class to MSMobileControlView .

Inside MSMobileControlView I have this code:

-(void)didMoveToSuperview
{
    NSLog(@"self.frame: %@", NSStringFromCGRect(self.frame));

    UIBUtton *levelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [levelButton setFrame:CGRectMake(0, 0, 150, 40)];
    [levelButton setTitle:@"Next Level" forState:UIControlStateNormal];
    [self addSubview:levelButton];
}

The NSLog output is:

self.frame: {{0, 0}, {0, 0}}

However I can still see the view on the screen and the button responds to taps as expected. I have no other code associated with MSMobileControlView . What is going on?

The Auto Layout runtime is assigning values to the frame later. If you want to see those assigned values, put your NSLog in viewDidLayoutSubviews .

If there's one piece of advice I would give you when starting out with Auto Layout, it is to forget frames. Just work with constraints. Let Auto Layout manipulate the frames on your behalf to give you the layout that your constraints specify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM