在安全区域内的屏幕顶部放置横幅? (而不是底部)

Placing a banner at the top of the screen within safe area? (rather than bottom)

我正在使用 IronSource 中的这段代码放置横幅,但它显示在底部,而不是顶部。

我想要做的是让横幅显示在顶部而不是底部,下面的代码工作正常,但显然显示在底部而不是顶部。

我尝试更改

y -= self.view.safeAreaInsets.bottom;

y -= self.view.safeAreaInsets.top;

但是没有用。

这是显示横幅的完整代码;

#pragma mark - Orientation delegate
- (void)orientationChanged:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.bannerView) {
            CGFloat y = self.view.frame.size.height - (self.bannerView.frame.size.height / 2);
            if (@available(ios 11.0, *)) {
                y -= self.view.safeAreaInsets.bottom;
            }
            self.bannerView.center = CGPointMake(self.view.frame.size.width / 2, y);
        }
    });
}
 
#pragma mark - Banner Delegate Functions
- (void)bannerDidLoad:(ISBannerView *)bannerView {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.bannerView = bannerView;
       
        CGFloat y = self.view.frame.size.height - (self.bannerView.frame.size.height / 2);
        if (@available(ios 11.0, *)) {
            y -= self.view.safeAreaInsets.bottom;
        }
        self.bannerView.center = CGPointMake(self.view.frame.size.width / 2, y);
       
        [self.view addSubview:self.bannerView];
    });
}

你真的应该使用自动布局/约束——那么你就不需要这些了。

但是,假设您有正当理由 NOT,请像这样尝试:

dispatch_async(dispatch_get_main_queue(), ^{
    if (self.bannerView) {
        CGFloat y = 0;
        if (@available(ios 11.0, *)) {
            y = self.view.safeAreaInsets.top;
        }
        self.bannerView.center = CGPointMake(self.view.frame.size.width / 2, y + self.bannerView.frame.size.height / 2);
    }
});

如果您想让您的生活更轻松,请将您的 bannerDidLoad 方法更改为:

- (void)bannerDidLoad:(ISBannerView *)bannerView {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.bannerView = bannerView;

        [self.view addSubview:self.bannerView];

        self.bannerView.translatesAutoresizingMaskIntoConstraints = false;
        [self.bannerView.widthAnchor constraintEqualToConstant:self.bannerView.frame.size.width].active = YES;
        [self.bannerView.heightAnchor constraintEqualToConstant:self.bannerView.frame.size.height].active = YES;
        [self.bannerView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = YES;
        if (@available(ios 11.0, *)) {
            [self.bannerView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor].active = YES;
        } else {
            [self.bannerView.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES;
        }
    });
}

并且您可以完全消除您的 - (void)orientationChanged:(NSNotification *)notification 方法。