[英]UIView doesn't add to UIViewController
我有一個視圖,當沒有互聯網連接時顯示,如果沒有互聯網連接,我會檢查是否已使用此方法還原。 首先在viewDidLoad
調用
-(void)checkInternet {
internetReach = [Reachability reachabilityForInternetConnection];
[internetReach startNotifier];
NetworkStatus netStatus = [internetReach currentReachabilityStatus];
switch (netStatus){
case ReachableViaWWAN:{
isReachable = YES;
NSLog(@"4g");
noInternetView.hidden = YES;
break;
}
case ReachableViaWiFi:{
isReachable = YES;
noInternetView.hidden = YES;
NSLog(@"wifi");
break;
}
case NotReachable:{
NSLog(@"NONE");
noInternetView = [[CheckInternetView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:noInternetView]; //IT IS NOT ADDED??
isReachable = NO;
[self checkInternet];
break;
}
}
}
如果沒有互聯網,就會一遍又一遍地調用該方法,但是為什么noIntenertView
現在視圖控制器上呢?
編輯
這是CheckInternetView類
#import "CheckInternetView.h"
@implementation CheckInternetView
- (id)initWithFrame:(CGRect)frame {
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
self = [super initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
if (self) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 60)];
label.textAlignment = NSTextAlignmentCenter;
label.numberOfLines = 2;
[label setCenter:CGPointMake(self.frame.size.width / 2 , self.frame.size.height / 2 - 25)];
label.text = @"You've lost your internet connection. Please connect to internet.";
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner.frame = CGRectMake(0, 0, 80, 80);
[spinner setCenter:CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2 + 40)];
[spinner startAnimating];
label.textColor = whiteColorAll;
spinner.color = whiteColorAll;
[self setBackgroundColor:[UIColor blackColor]];
[self addSubview: spinner];
[self addSubview: label];
}
return self;
}
由於您是在主UI線程上調用checkInternet
並創建無限遞歸循環,因此沒有時間更新UI。 它只有在您從viewDidLoad
返回后才會更新。 但這只有在您真正擁有有效的互聯網連接后才會發生。 如果您沒有,則將循環播放。
若要解決此問題: checkInternet
的調用移到后台線程中。 如果然后需要顯示視圖,請確保再次在主線程上發生。
在這里看看如何正確創建新的后台線程。 在這里查看如何在主線程上再次運行需要的UI代碼。
請注意 ,由於CheckInternetView
添加它們,最終可能會產生大量CheckInternetView
實例。 如果尚不存在,最好只創建並添加一個。
另外,您的代碼將占用大量性能,甚至可能導致崩潰,因為您只是遞歸而沒有適當的超時或中斷條件。 最好每隔一秒鍾或每隔半秒或在該范圍內的某個時間間隔檢查一次Internet。 而且,您可能希望以連續循環而不是遞歸的方式進行操作,以減少對堆和堆棧的影響。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.