2013-10-07 4 views
1

Я действительно пытаюсь понять, как обращаться с поворотом. Я читал многочисленные сообщения здесь, но не могу получить элементы, которые нужно добавить к экрану ландшафта правильным образом и в правильном положении.iPhone Portrait/Landscape and Coordinate System

Например, у меня есть портретный вид (320x480) и создайте большую кнопку в позиции (0,0). Я ожидаю, что он появится в верхнем левом углу.

Когда я поворачиваю устройство по часовой стрелке в альбомную ориентацию (480x320), я ожидаю, что координаты (0,0) также будут в левом верхнем углу, но это не так. Моя кнопка неправильно отображается в правом верхнем углу, а текст на кнопке идет по экрану, а не по всему ландшафту/в широком направлении.

Я приложу свой (грязный) код в надежде, что он проливает свет на то, что я пытаюсь сделать.

Я ошибаюсь, полагая, что могу повернуть систему координат с помощью устройства, чтобы система координат стала 480x320 в ландшафтном режиме с 0,0 в левом верхнем углу? Если я не ошибаюсь ... как мне это достичь?

#include "ContainerVC.h" 

@interface UIApplication (AppDimensions) 

+(CGSize) currentSize; 
+(CGSize) sizeInOrientation:(UIInterfaceOrientation)orientation; 

@end 


@implementation UIApplication (AppDimensions) 


+(CGSize) currentSize 
{ 
    return [UIApplication sizeInOrientation:[UIApplication sharedApplication].statusBarOrientation]; 
} 

+(CGSize) sizeInOrientation:(UIInterfaceOrientation)orientation 
{ 
    CGSize size = [UIScreen mainScreen].bounds.size; 

    UIApplication *application = [UIApplication sharedApplication]; 

    if(UIInterfaceOrientationIsLandscape(orientation)) 
    { 
    size = CGSizeMake(size.height, size.width); 
    } 

    if (application.statusBarHidden == NO) 
    size.height -= MIN(application.statusBarFrame.size.width, application.statusBarFrame.size.height); 

    return size; 
} 


@end 



@interface ContainerVC() 

@end 

@implementation ContainerVC 

int  g_MaxPixelHeight; 
int  g_MaxPixelWidth; 

-(void) addMyContent 
{ 
    // TEST BUTTON !! 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    button.frame = CGRectMake(0, 0, 200, 200); 

    [button setBackgroundColor: [UIColor redColor]]; 

    // Configure title(s) 
    button.titleLabel.lineBreakMode = UILineBreakModeWordWrap; 
    button.titleLabel.textAlignment = UITextAlignmentCenter; 

    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
    [button setTitleShadowColor:[UIColor colorWithRed:.25 green:.25 blue:.25 alpha:1] forState:UIControlStateNormal]; 
    [button setTitleShadowOffset:CGSizeMake(0, -1)]; 
    [button setFont:[UIFont boldSystemFontOfSize:40]]; 

    [button setTitle: @"TITLE" forState:UIControlStateNormal]; 

    [self.view addSubview:button]; 
    return; 
} 

-(void) loadView 
{ 
    // PDS> Stack overflow says don't call this but I get errors if I don't!! 
    [super loadView]; 
} 


-(void) viewDidLoad 
{ 
    NSLog(@"** VIEW DID LOAD"); 

    [super viewDidLoad]; 

    g_ContainerVC = self; 

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

- (BOOL)canBecomeFirstResponder 
{ 
    return YES; 
} 

-(void) viewDidAppear:(BOOL)animated 
{ 
    NSLog(@"** VIEW DID APPEAR"); 

    [super viewDidAppear:animated]; 

    [self becomeFirstResponder]; 
} 

-(void) viewWillDisappear:(BOOL)animated 
{ 
    [self resignFirstResponder]; 

    [super viewWillDisappear:animated]; 
} 

-(void) viewWillAppear: (BOOL) animated 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil]; 
} 

-(void) viewDidDisappear:(BOOL) animated 
{ 
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil]; 
} 

-(void) adjustViewsForOrientation:(UIInterfaceOrientation) orientation 
{ 
} 

-(void) orientationChanged: (NSNotification *) notification 
{ 
    CGSize screenSize = [UIApplication currentSize]; 

    NSLog(@"** orientationChanged ** ScreenSize: %d x %d", (int) screenSize.width, (int) screenSize.height); 

    g_MaxPixelWidth = screenSize.width; 
    g_MaxPixelHeight = screenSize.height; 

    return; 
} 

-(void) didRotate: (id) sender 
{ 
    UIDeviceOrientation orientation  = [[UIDevice currentDevice] orientation]; 
    UIInterfaceOrientation cachedOrientation = [self interfaceOrientation]; 

    if(orientation == UIDeviceOrientationUnknown || 
     orientation == UIDeviceOrientationFaceUp || 
     orientation == UIDeviceOrientationFaceDown) 
    { 
    orientation = (UIDeviceOrientation)cachedOrientation; 
    } 

    if(orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight) 
    { 
    if(orientation == UIDeviceOrientationLandscapeLeft) 
     [UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationLandscapeLeft; 
    else 
    if(orientation == UIDeviceOrientationLandscapeRight) 
     [UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationLandscapeRight; 

    CGSize screenSize = [UIApplication currentSize]; 

    g_MaxPixelWidth = screenSize.width; 
    g_MaxPixelHeight = screenSize.height; 

    NSLog(@"** didRotate: LANDSCAPE: %d x %d", g_MaxPixelWidth, g_MaxPixelHeight); 
    } 

    if(orientation == UIDeviceOrientationPortrait || orientation == UIDeviceOrientationPortraitUpsideDown) 
    { 
    if(orientation == UIDeviceOrientationPortrait) 
     [UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationPortrait; 
    else 
    if(orientation == UIDeviceOrientationPortraitUpsideDown) 
     [UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationPortraitUpsideDown; 

    CGSize screenSize = [UIApplication currentSize]; 

    g_MaxPixelWidth = screenSize.width; 
    g_MaxPixelHeight = screenSize.height; 

    NSLog(@"** didRotate: PORTRAIT: %d x %d", g_MaxPixelWidth, g_MaxPixelHeight ); 
    } 

    for (UIView *view in self.view.subviews) 
    { 
    [view removeFromSuperview]; 
    } 
} 


-(void) layoutSubviews 
{ 
    NSLog(@"- layoutSubviews"); 
} 

- (void) viewWillLayoutSubviews 
{ 
    NSLog(@"- viewWillLayoutSubviews"); 

    [self addMyContent]; 
} 

- (NSUInteger)supportedInterfaceOrientations 
{ 
    return UIInterfaceOrientationMaskAllButUpsideDown; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return YES; 
} 

@end 
+0

FYI: 'layoutSubviews' должен всегда вызывать' [super layoutSubviews] '. – progrmr

+0

@progrmr: Спасибо. Поможет ли это решить мою проблему? – SparkyNZ

ответ

0

Я думаю, что это может быть ответом - используя метод CGAffineTransformMakeRotation ..

this Stackoverflow posting

В самом деле, это решить мою проблему.

 Смежные вопросы

  • Нет связанных вопросов^_^