Tepmnthar Tepmnthar - 1 month ago 12
iOS Question

How can I use autolayout on a view which layouts its subviews manually

I have a third party widget which I want to autolayout in my controller view. While I found that the widget manually layout its subviews in its

initWithFrame:
method.

I could only make the frame of the widget as I expect, but the frames of subviews on it are ZERO.

How can I mix those together. I can't modify the widget. And I can do nothing in my
didLayoutSubivews
, and calling
[self setNeedLayout]
[self layoutIfNeeded]
before I create the widget instance, because it layouts its subviews immediately when initializing.

Answer

I'm not sure why you say you can do nothing in didLayoutSubviews. If the widget only sets up its views in initWithFrame and never recalculates their dimensions, it seems that's the only place you can do something. Two options I can see are:

1) You need to manually force the widget to re-initialise once your view constraints have been satisfied. Not the best really.

- (void)didLayoutSubviews {
     [super didLayoutSubviews];

    self.myWidget = [self.myWidget initWithFrame: self.myWidgetContainer.frame];
}

2) Only initialise the widget once your views are set up.

- (void)didLayoutSubviews {
    [super didLayoutSubviews];

    if (!self.myWidget) {    
        self.myWidget = [self.myWidget initWithFrame: self.myWidgetContainer.frame];
        [self.myWidgetContainer addSubview:self.myWidget];
    }
}