![](/img/trans.png)
[英]On iOS, can we get to the main UIWindow object from the UIScreen object?
[英]Positioning UIWindow in UIScreen in iOS
我需要向我的應用添加其他UIWindow
。 無論設備的方向如何,此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
位置都是正確的。 但是,當我旋轉設備時-我的窗口發瘋了,它跳到了意外的位置,我不知道為什么。
請幫忙!
在以下情況下一切正常:
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
非常感謝Cocoa-Chat和max.lunin :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.