方向更改时重绘自定义视图的最佳方法

时间:2013-08-09 19:23:29

标签: ios

我有自定义视图:

-(id)initWithFrame:(CGRect)frame
{
    CGRect frameRect = CGRectMake(0, NAVIGATION_BAR_HEIGHT , frame.size.width, 4 * ROW_HEIGHT + NAVIGATION_BAR_HEIGHT + MESSAGE_BODY_PADDING);
    self = [super initWithFrame:frameRect];
    if (self) {
        _selectionViewWidth = &frame.size.width;

        [self initView];
    }
    return self;
}

-(void)initView
{
    CGRect sectionSize = CGRectMake(0, 0 , *(_selectionViewWidth), ROW_HEIGHT * 4);
    _selectionView = [[UIView alloc] initWithFrame:sectionSize];
    [_selectionView setBackgroundColor:[UIColor clearColor]];

我在下一个方向使用View Controller:

_mailAttributesView = [[MailAttributesView alloc]initWithFrame:self.view.frame];
    _mailAttributesView.delegate = self;
    [self.view addSubview:_mailAttributesView];

因此当方向从P变为L时,我有下一个问题:

enter image description here

获取方向更改回调和重绘自定义视图的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您可能需要覆盖UIView layoutSubviews方法并继续手动布局子视图(看起来像/来自/ cc /主题控件)。

或者,您可以更好地配置子视图弹簧/支柱(或自动布局约束)以进行自动布局。您可以在代码中或通过笔尖或故事板执行此操作。

编辑:其他信息,因为您似乎没有获得有关方向更改的layoutSubviews。

我的猜测是viewcontroller-view也没有调整/重新定位你的MailAttributes视图。

还不清楚将MailAttributesView添加到veiwcontroller视图的时间/位置。如果你在viewDidLoad中执行它,你的viewcontroller视图可能有也可能没有有效的帧大小(取决于它是否从nib加载)。最好不要在viewDidLoad中依赖viewcontroller-view框架进行布局。

相反,在viewWillLayoutSubviews中布局任何viewcontroller-view子视图。你的viewcontroller-view框架将被设置。

其他人可能会指出您可以在viewDidLoad中为任何子视图设置autoresizingFlags,但是有一些问题。主要是如果父视图的大小为零,并且您的子视图将被插入但是已定义了弹簧/支柱以将它们粘贴到父视图边缘。

整体IMO的最佳解决方案是为视图控制器视图中包含的所有内容设置自动布局约束。