繁体   English   中英

UIView不会添加到UIViewController

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM