簡體   English   中英

在iOS中的UIScreen中定位UIWindow

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM