我正在尝试通过单例处理我的 iAd,因为我在多个 View Controller 中使用这些横幅。现在我对这些对象存储的内容感到困惑,因为当显示广告或发生错误时,我在每个 View Controller 上以不同方式移动它们。这是我的代码:
单例:
+ (MySingleton *)sharedInstance {
static dispatch_once_t once;
static MySingleton * sharedInstance;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (id)init
{
if (self = [super init]) {
if ([ADBannerView instancesRespondToSelector:@selector(initWithAdType:)]) {
self.bannerView = [[ADBannerView alloc] initWithAdType:ADAdTypeBanner];
} else {
self.bannerView = [[ADBannerView alloc] init];
}
}
return self;
}
这里是如何初始化的:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//iAd
if(![[NSUserDefaults standardUserDefaults] objectForKey:kInAppPurchaseNoAds]){
self.bannerView = [MySingleton sharedInstance].bannerView;
self.bannerView.delegate = self;
self.bannerView.frame = CGRectOffset(self.bannerView.frame, 0, self.view.frame.size.height);
[self.view addSubview:self.bannerView];
}
}
委托(delegate)方法:
- (void)showBanner
{
if(!self.isBannerVisible){
[self.view layoutIfNeeded];
[UIView animateWithDuration:0.5
animations:^{
//Restore the constraint
self.mainContainerToSuperviewConstraint.constant = 50;
//Move the banner on
self.bannerView.frame = CGRectOffset(self.bannerView.frame, 0, -50);
[self.view layoutIfNeeded];
} completion:^(BOOL finished) {
self.isBannerVisible = YES;
}];
}
}
- (void)hideBanner
{
if(self.isBannerVisible){
[self.view layoutIfNeeded];
[UIView animateWithDuration:0.5
animations:^{
//Restore the constraint
self.mainContainerToSuperviewConstraint.constant = 0;
//Move the banner off
self.bannerView.frame = CGRectOffset(self.bannerView.frame, 0, self.bannerView.frame.size.height);
[self.view layoutIfNeeded];
} completion:^(BOOL finished) {
self.isBannerVisible = NO;
}];
}
}
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
[self showBanner];
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
[self hideBanner];
}
现在让我感到困惑的是,如果用户在另一个 View 中还有一个 iAd,其中带有可见横幅的矩形位于距离底部 75 处,我是否必须再次检查横幅 View 的位置屏幕而不是 50?还是这些位置不影响 AdBannerView 而只影响每个类中的单个对象?!我的意思是,如果他在另一个 View 中并且代码将横幅从底部移动到 75 像素,那么这 75 像素是否存储在我的单例 AdView 中?那么原始 View 的横幅现在位于 75 而不是 50?
最佳答案
我建议不要为 View 使用单例 - 一个 View 实例只能是 1 个 View 的 subview ,因此您需要跟踪添加/删除它,并且每次再次添加时都需要设置框架一个 subview 。你最好有某种基础 View Controller 来共享实例化逻辑和横幅的控制。
关于iOS:iAd 单例混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28325751/