I am writing iOS application for iPad that require custom layout.
The layout from portrait and landscape are totally difference, so it can't be solve by using UIAutoResizingMask.
I try to use the layoutSubview Method, but I detected that layout subview is called a lot (from UIScrollView). How can i redu开发者_StackOverflow中文版ce the layoutSubview call to optimize the code , or I should call it by my self when ever the device is rotated.
Thank.
For different landscape and portrait design use view controllers methods such as
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;
If you create your custom view depending on current orientation, check this orientation by UIDeviceOrientationDidChangeNotification
notification and write appropriate code.
in one of the init~
methods:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangedOrientation:) name:UIDeviceOrientationDidChangeNotification object:nil];
And action
- (void) didChangedOrientation:(NSNotification *)sender{
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (UIDeviceOrientationIsPortrait(orientation)){}}
The fact that layoutSubviews
gets called by a child UIScrollView
is very unfortunate, but there's an (ugly) workaround:
@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
Not the best solution but seems to work reasonably well.
You should not do expensive calculations in layoutSubviews:
Speaking from experience I would personally only adjust your layout based upon deviceDidRotateSelector notifications. I have an updatePortrait method and an updateLandscape method and call whichever is necessary.
精彩评论