添加&在Swift中删除视图覆盖 [英] Adding & Removing A View Overlay in Swift

查看:134
本文介绍了添加&在Swift中删除视图覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从此问题开始:从Swift中的任何类加载屏幕

问题:加载叠加视图将显示,但在调用hideOverlayView()时不会隐藏。奇怪的是,重叠会在一段时间后(在它出现后15到30秒)消失。

Issue: The loading overlay view will display but will not hide when hideOverlayView() is called. Oddly however, the overlay disappears after some time (15 to 30 seconds after it appears)

代码:包含在 FirstController.swift

Code: Contained in FirstController.swift

public class LoadingOverlay{

var overlayView = UIView()
var activityIndicator = UIActivityIndicatorView()

class var shared: LoadingOverlay {
    struct Static {
        static let instance: LoadingOverlay = LoadingOverlay()
    }
    return Static.instance
}

public func showOverlay() {
    if  let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate,
        let window = appDelegate.window {
            overlayView.frame = CGRectMake(0, 0, 80, 80)
            overlayView.center = CGPointMake(window.frame.width / 2.0, window.frame.height / 2.0)
            overlayView.backgroundColor = MyGlobalVariables.UICOLORGREEN
            overlayView.clipsToBounds = true
            overlayView.layer.cornerRadius = 10

            activityIndicator.frame = CGRectMake(0, 0, 40, 40)
            activityIndicator.activityIndicatorViewStyle = .WhiteLarge
            activityIndicator.center = CGPointMake(overlayView.bounds.width / 2, overlayView.bounds.height / 2)

            overlayView.addSubview(activityIndicator)
            window.addSubview(overlayView)

            activityIndicator.startAnimating()
    }
}

public func hideOverlayView() {
    activityIndicator.stopAnimating()
    overlayView.removeFromSuperview()
}
}

DataManager.swift 中的函数中调用:

LoadingOverlay.shared.showOverlay()

解决方案:

我在后台线程调用。根据下面的答案,调用:

I was calling on a background thread. As per the answers below, call as:

dispatch_async(dispatch_get_main_queue(), { // This makes the code run on the main thread
  LoadingOverlay.shared.hideOverlayView()          
})


推荐答案

您是从后台主题调用 hideOverlayView()吗?如果你是,你应该确保它运行在主线程:

Are you calling hideOverlayView() from a background thread? If you are, you should make sure it runs on the main thread:

dispatch_async(dispatch_get_main_queue(), { // This makes the code run on the main thread
  LoadingOverlay.shared.hideOverlayView()          
})

这篇关于添加&在Swift中删除视图覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆