2015-06-03 27 views
1

我需要將其他UIWindow添加到我的應用程序。這UIWindow應始終儘管設備的方向定位在屏幕的右下角,這裏的草圖: enter image description here在iOS中的UIScreen中定位UIWindow

我試圖繼承一個UIWindow這樣才能夠設置大小和窗口的邊緣:

@interface MyWindow : UIWindow 

@property (nonatomic) CGSize size; 
@property (nonatomic) CGFloat margin; 

@end 

@implementation MyWindow 

- (id)initWithSize:(CGSize)size andMargin:(CGFloat)margin { 
    self.size = size; 
    self.margin = margin; 
    return [self initWithFrame:[self calculateFrame]]; 
} 

- (CGRect)calculateFrame { 
    return CGRectMake([[UIScreen mainScreen] bounds].size.width-self.size.width-self.margin, [[UIScreen mainScreen] bounds].size.height-self.size.height-self.margin, self.size.width, self.size.height); 
} 

- (id)initWithFrame:(CGRect)frame { 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
     [self assignObservers]; 
    } 
    return self; 
} 

-(void)assignObservers { 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(statusBarDidChangeFrame:) 
               name:UIDeviceOrientationDidChangeNotification 
               object:nil]; 
} 

- (void)statusBarDidChangeFrame:(NSNotification *)notification { 
    [self setFrame:[self calculateFrame]]; 
} 

@end 

一切都很好啓動!無論在初始啓動方面是什麼新的UIWindow位置都是正確的。但是,當我旋轉設備 - 我的窗戶變得瘋狂,它跳轉到意想不到的位置,我不知道爲什麼。

請幫忙!

+0

有人嗎?請,我真的需要幫助... – oleynikd

回答

1

一切工作正常,如果:

dispatch_async(dispatch_get_main_queue(), ^{ 
    [self setFrame:[self calculateFrame]]; 
}); 

所以完整的工作代碼如下所示:

@interface MyWindow : UIWindow 

@property (nonatomic) CGSize size; 
@property (nonatomic) CGFloat margin; 

@end 

@implementation MyWindow 

- (id)initWithSize:(CGSize)size andMargin:(CGFloat)margin { 
    self.size = size; 
    self.margin = margin; 
    return [self initWithFrame:[self calculateFrame]]; 
} 

- (CGRect)calculateFrame { 
    return CGRectMake([[UIScreen mainScreen] bounds].size.width-self.size.width-self.margin, [[UIScreen mainScreen] bounds].size.height-self.size.height-self.margin, self.size.width, self.size.height); 
} 

- (id)initWithFrame:(CGRect)frame { 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
     [self assignObservers]; 
    } 
    return self; 
} 

-(void)assignObservers { 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(statusBarDidChangeFrame:) 
               name:UIApplicationDidChangeStatusBarOrientationNotification 
               object:nil]; 
} 

- (void)statusBarDidChangeFrame:(NSNotification *)notification { 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self setFrame:[self calculateFrame]]; 
    }); 
} 

@end 

非常感謝可可聊天和max.lunin :)