swift 为什么UIActivityIndicatorView只在第一次可见时才动画?

rta7y2nd  于 2023-02-21  发布在  Swift
关注(0)|答案(1)|浏览(119)

我根据网络状态更改导航栏标题,当没有连接时,我显示为UIActivityIndicatorView,沿着是“等待网络”。这在我第一次关闭网络连接时效果很好,当我第二次禁用它时,“等待网络”和活动指示器出现,但是,它没有动画。

override func viewDidLoad() {
        label.text = "Waiting for network"
        label.font = UIFont.systemFont(ofSize: 17)
        label.textColor = .black
        
     
        containerView.addSubview(self.activityIndicator)
        containerView.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        self.activityIndicator.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.activityIndicator.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
            self.activityIndicator.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
            label.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
            label.leadingAnchor.constraint(equalTo: self.activityIndicator.trailingAnchor, constant: 8),
            containerView.widthAnchor.constraint(equalTo: label.widthAnchor, constant: self.activityIndicator.frame.width + 8)
        ])
        
        super.viewDidLoad()
    }
    
    
    
    func onUpdate(_ isConnected: Bool) {
        print("isInternetConnected changed to: \(isConnected)")

        if isConnected {
            DispatchQueue.main.async {
                
                self.navigationItem.titleView = nil
                self.activityIndicator.stopAnimating()
                self.navigationItem.title = "Chats"
            }
        } else {
            DispatchQueue.main.async {
                self.navigationItem.titleView = 

self.containerView
 self.activityIndicator.startAnimating()

            }
        }
    } 

  let activityIndicator: UIActivityIndicatorView = {
        let activityIndicator = UIActivityIndicatorView()
        activityIndicator.style = .medium
        activityIndicator.hidesWhenStopped = true
        activityIndicator.color = .black
        activityIndicator.startAnimating()
        return activityIndicator
    }()
mnowg1ta

mnowg1ta1#

您需要通过调用self.activityIndicator.startAnimating()来启动动画,因为当isConnected为true时会停止动画

if isConnected {
        DispatchQueue.main.async {
            
            self.navigationItem.titleView = nil
            if self.activityIndicator.isAnimating {
                 self.activityIndicator.stopAnimating()
            }
            self.navigationItem.title = "Chats"
        }
    } else {
        DispatchQueue.main.async {
            self.navigationItem.titleView = self.containerView
            if !self.activityIndicator.isAnimating {
                 self.activityIndicator.startAnimating() // <<< --- here
            }
        }
    }

相关问题