Swift UIKit 예제: 로딩 인디케이터 화면
Swift UIKit 예제: 로딩 인디케이터 화면
소개
UIKit에서 특정 로딩 상황이 발생할 때 로딩 인디케이터를 띄우는 예제입니다. 외부 라이브러리를 사용하지 않고 기본 제공 요소로 만들었습니다.
https://giphy.com/gifs/hH9JzdEtDTTOWxSTCf
https://giphy.com/gifs/kvqcJeJoeClyln5Oe8
코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import UIKit
struct LoadingIndicatorUtil {
static let `default` = LoadingIndicatorUtil()
private init() {}
private let TAG = 95834114
enum Style {
case clear, blur
}
/// 로딩 인디케이터 창을 띄웁니다.
func show(_ viewController: UIViewController, style: Style = .clear, text: String = "") {
let container: UIView = UIView()
container.frame = CGRect(x: 0, y: 0, width: 80, height: 80) // Set X and Y whatever you want
container.backgroundColor = .clear
container.tag = TAG
if text.isNotEmpty {
let label = UILabel(frame: .init(x: 0, y: 0, width: 200, height: 30))
label.numberOfLines = 0
label.text = text
label.sizeToFit()
label.center = viewController.view.center
label.frame.origin.y += 50
container.addSubview(label)
label.textColor = style == .blur ? .white : nil
}
let activityView = UIActivityIndicatorView(style: .large)
activityView.center = viewController.view.center
container.addSubview(activityView)
switch style {
case .clear:
break
case .blur:
activityView.color = .white
let blurEffect = UIBlurEffect(style: .dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = viewController.view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
blurEffectView.tag = TAG
viewController.view.addSubview(blurEffectView)
}
viewController.view.addSubview(container)
activityView.startAnimating()
}
/// 현재 떠있는 로딩 인디케이터 창을 제거합니다.
func hide(_ viewController: UIViewController) {
viewController.view.subviews.forEach {
if $0.tag == TAG {
$0.removeFromSuperview()
}
}
}
}
사용 방법
This post is licensed under
CC BY 4.0
by the author.

