Search code examples
iosobjective-cautoresizingmask

iOS Component is automatically resizing but I don't know where and why


I am using this control (RDVCalendarView) and I want to little customize it. I want to change height of calendar so it wouldn't be height as whole controller but little smaller. So in loadView I change code to this:

CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
applicationFrame.size.height = 200;

_calendarView = [[RDVCalendarView alloc] initWithFrame:applicationFrame];
[_calendarView setAutoresizingMask:UIViewAutoresizingNone];
[_calendarView setSeparatorStyle:RDVCalendarViewDayCellSeparatorTypeHorizontal];
[_calendarView setBackgroundColor:[UIColor whiteColor]];
[_calendarView setDelegate:self];
self.view = _calendarView;

In whole initWithFrame method of RDVCalendarView there is correct size of height which I set. But after viewWillAppear there is layoutSubviews call and has 504 size of height. I don't know what happens but it looks like height is autoresizing to height of controller. I just don't know where it could be. Thanks for help


Solution

  • Usually you don't directly set the frame of a UIViewController's main view, see https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/AdoptingaFull-ScreenLayout/AdoptingaFull-ScreenLayout.html

    Instead, you simply add the view you want to resize as a subview to your view controller's root view. To do that, simply change the method from loadView to viewDidLoad. At that point, the system has already created a default UIView for you and assigned it to the view controller's view property.

    Change your code to this:

    - (void)viewDidLoad {
        CGRect calendarFrame = self.view.frame;
        calendarFrame.size.height = 200;
    
        _calendarView = [[RDVCalendarView alloc] initWithFrame:calendarFrame];
        [_calendarView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
        [_calendarView setSeparatorStyle:RDVCalendarViewDayCellSeparatorTypeHorizontal];
        [_calendarView setBackgroundColor:[UIColor whiteColor]];
        [_calendarView setDelegate:self];
    
        [self.view addSubview:_calendarView];
    }
    

    That should do the trick.