何时在iOS中使用layoutSubview?

5
我正在编写针对iPad的iOS应用程序,需要自定义布局。
由于纵向和横向的布局完全不同,因此不能使用UIAutoResizingMask来解决。
我试图使用layoutSubview方法,但是我发现它被频繁调用(来自UIScrollView)。 如何减少layoutSubview的调用以优化代码,或者是否应该在设备旋转时手动调用它。
谢谢。
4个回答

4

针对不同的横屏和竖屏设计,可以使用视图控制器方法,例如

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;

如果您创建了一个依赖于当前方向的自定义视图,请通过 UIDeviceOrientationDidChangeNotification 通知来检查该方向,并编写适当的代码。

在其中一个 init~ 方法中:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangedOrientation:) name:UIDeviceOrientationDidChangeNotification object:nil];

行动起来

- (void) didChangedOrientation:(NSNotification *)sender{
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (UIDeviceOrientationIsPortrait(orientation)){}}

3

layoutSubviewsUIScrollView调用的事实非常不幸,但有一个(丑陋的)解决方法:

@interface MyClass : UIView {
    BOOL reallyNeedsLayout_;
}
@end

@implementation MyClass

- (void)setNeedsLayout
{
    [super setNeedLayout];
    reallyNeedsLayout_ = YES;
}

- (void)setFrame:(CGRect)rect
{
    [super setFrame:rect];
    reallyNeedsLayout_ = YES;
}

- (void)layoutSubviews
{
    if (!reallyNeedsLayout_) return;
    reallyNeedsLayout_ = NO;

    // Do layouting.
}
@end

不是最好的解决方案,但似乎运作得相当不错。


到目前为止,先生,这个问题的最佳解决方案是什么? - Isara Rungvitayakul

1

在layoutSubviews中不应进行昂贵的计算:


0

从经验来看,我个人只会根据 deviceDidRotateSelector 通知调整您的布局。 我有一个 updatePortrait 方法和一个 updateLandscape 方法,并调用所需的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接