在 iOS 中将 UIWindow 定位在 UIScreen 中

Positioning UIWindow in UIScreen in iOS

我需要向我的应用添加额外的 UIWindow。不管设备的方向如何,这个 UIWindow 应该始终位于屏幕的右下角,这是草图:

我试过像这样对 UIWindow 进行子类化,以便能够设置 window:

的大小和边距
@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 位置都是正确的。但是当我旋转设备时 - 我的 window 变得疯狂,它跳到意想不到的位置,我不明白为什么。

请帮忙!

一切正常,如果:

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 :)