Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีใช้ MBProgressHUD กับ Swift

MBProgressHUD เป็น Library แสดง Loading Indicator (HUD) ยอดนิยม ติดตั้งผ่าน CocoaPods

ติดตั้ง (CocoaPods)


# Podfile
pod 'MBProgressHUD', '~> 1.2.0'

# Terminal
pod install

การใช้งานพื้นฐาน


import MBProgressHUD

// แสดง HUD
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.label.text = "Loading..."
hud.detailsLabel.text = "Please wait"
hud.isUserInteractionEnabled = false // บล็อก Touch

// ซ่อน HUD
MBProgressHUD.hide(for: self.view, animated: true)

Extension UIViewController ใช้งานง่าย


extension UIViewController {
    func showHUD(title: String = "Loading", detail: String? = nil) {
        let hud = MBProgressHUD.showAdded(to: view, animated: true)
        hud.label.text = title
        hud.detailsLabel.text = detail
        hud.isUserInteractionEnabled = false
        hud.bezelView.style = .solidColor
        hud.bezelView.color = UIColor(white: 0, alpha: 0.7)
        hud.contentColor = .white
    }
    
    func hideHUD() {
        MBProgressHUD.hide(for: view, animated: true)
    }
    
    func showSuccess(_ message: String) {
        let hud = MBProgressHUD.showAdded(to: view, animated: true)
        hud.mode = .customView
        hud.customView = UIImageView(image: UIImage(systemName: "checkmark.circle.fill"))
        hud.label.text = message
        hud.hide(animated: true, afterDelay: 1.5)
    }
    
    func showError(_ message: String) {
        let hud = MBProgressHUD.showAdded(to: view, animated: true)
        hud.mode = .customView
        hud.customView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
        hud.label.text = message
        hud.hide(animated: true, afterDelay: 2)
    }
}

// ใช้งาน
showHUD(title: "Logging in...", detail: "Please wait")
login { [weak self] success in
    self?.hideHUD()
    if success { self?.showSuccess("Login successful") }
    else { self?.showError("Login failed") }
}

Mode ต่างๆ

  • .indeterminate - Spinner (Default)
  • .determinate - Progress Bar (0.0 - 1.0)
  • .annularDeterminate - วงกลม Progress
  • .customView - Custom Icon (Success/Error)
  • .text - Text Only

Progress HUD


let hud = MBProgressHUD.showAdded(to: view, animated: true)
hud.mode = .determinate
hud.label.text = "Downloading..."

// Update Progress
for i in 1...100 {
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
        hud.progress = Float(i) / 100.0
    }
}

Alternative Libraries

  • SVProgressHUD - เรียบง่าย, Class Methods
  • ProgressHUD - Lightweight
  • Loaf - Toast Style (ไม่ใช่ HUD)
  • SwiftUI: ใช้ .overlay + ProgressView แทน