How to display an activity indicator with text on iOS 8 with Swift?

前端 未结 14 2195
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 08:58

I wanna show, programmatically, an activity indicator with text, like the one in the Photos app (after editing and saving a picture). How can I do this?

14条回答
  •  悲&欢浪女
    2020-11-27 09:58

    Xcode 10.1 • Swift 4.2

    import UIKit
    
    class ProgressHUD: UIVisualEffectView {
    
        var title: String?
        var theme: UIBlurEffect.Style = .light
    
        let strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
        let activityIndicator = UIActivityIndicatorView()
    
        init(title: String, theme: UIBlurEffect.Style = .light) {
            super.init(effect: UIBlurEffect(style: theme))
    
            self.title = title
            self.theme = theme
    
            [activityIndicator, strLabel].forEach(contentView.addSubview(_:))
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override func didMoveToSuperview() {
            super.didMoveToSuperview()
    
            if let superview = self.superview {
                frame = CGRect(x: superview.frame.midX - strLabel.frame.width / 2,
                               y: superview.frame.midY - strLabel.frame.height / 2, width: 160, height: 46)
    
                layer.cornerRadius = 15.0
                layer.masksToBounds = true
    
                activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
                activityIndicator.startAnimating()
    
                strLabel.text = title
                strLabel.font = .systemFont(ofSize: 14, weight: UIFont.Weight.medium)
    
                switch theme {
                case .dark:
                    strLabel.textColor = .white
                    activityIndicator.style = .white
                default:
                    strLabel.textColor = .gray
                    activityIndicator.style = .gray
                }
            }
    
        }
    
        func show() {
            self.isHidden = false
        }
    
        func hide() {
            self.isHidden = true
        }
    }
    

    Use:

    let progress = ProgressHUD(title: "Authorization", theme: .dark)
    [progress].forEach(view.addSubview(_:))
    

提交回复
热议问题