initWithCoder shows wrong frame in ios

1.3k views Asked by At

I am using storyboard in my project. Storyboard has a custom view with auto layout.

CustomView.h

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {

        NSLog (@"view: %f", self.frame.size.width);   //Returns wrong
        NSLog (@"view: %f", self.bounds.size.width);  //Returns wrong
}
return self;
}

If i run the app, it shows wrong frame.

Help me to solve this

2

There are 2 answers

4
Leo On

Because in initWithCoder,the constraints has not been applied to the view.

Example:

Code

-(void)viewDidAppear:(BOOL)animated{
    NSLog (@"viewDidAppear: %f", self.testview.frame.size.width);
}
-(void)viewDidLayoutSubviews{
    NSLog (@"viewDidLayoutSubviews: %f", self.testview.frame.size.width);
}
-(void)awakeFromNib{
    NSLog (@"awakeFromNib: %f", self.testview.frame.size.width);
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        NSLog (@"initWithCoder: %f", self.testview.frame.size.width);
    }
    return self;
}

And log

2015-06-11 19:09:27.647 OCTest[717:20692] initWithCoder: 0.000000
2015-06-11 19:09:27.649 OCTest[717:20692] awakeFromNib: 0.000000
2015-06-11 19:09:27.696 OCTest[717:20692] viewDidLayoutSubviews: 320.000000
2015-06-11 19:09:27.746 OCTest[717:20692] viewDidAppear: 320.000000
0
Mikhey  Stepanov On

I met the same problem, if you want to take the size of screen in InitWithCoder method - take it this way

CGFloat x = [UIScreen mainScreen].bounds.size.width;
CGFloat y = [UIScreen mainScreen].bounds.size.height;

Not from the still-not-existing bounds of the UIView, but out of the UIScreen.