/
Toast.swift
74 lines (60 loc) · 2.41 KB
/
Toast.swift
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
62
63
64
65
66
67
68
69
70
71
72
73
74
import Foundation
@objc(CAPToastPlugin)
public class CAPToastPlugin : CAPPlugin {
var toast: UILabel?
@objc func show(_ call: CAPPluginCall) {
guard let text = call.get("text", String.self) else {
call.error("text must be provided and must be a string.")
return
}
let durationType = call.get("duration", String.self, "short")!
let duration = durationType == "long" ? 3500 : 2000
let position = call.get("position", String.self, "bottom")
DispatchQueue.main.async {
let vc = self.bridge!.viewController
let maxSizeTitle : CGSize = CGSize(width: vc.view.bounds.size.width-32, height: vc.view.bounds.size.height)
let lb = UILabel()
lb.backgroundColor = UIColor.black.withAlphaComponent(0.6)
lb.textColor = UIColor.white
lb.textAlignment = .center
lb.text = text
lb.alpha = 0
lb.layer.cornerRadius = 18
lb.clipsToBounds = true
lb.lineBreakMode = .byWordWrapping
lb.numberOfLines = 0
var expectedSizeTitle : CGSize = lb.sizeThatFits(maxSizeTitle)
// UILabel can return a size larger than the max size when the number of lines is 1
let minWidth = min(maxSizeTitle.width, expectedSizeTitle.width)
let minHeight = min(maxSizeTitle.height, expectedSizeTitle.height)
expectedSizeTitle = CGSize(width: minWidth, height: minHeight)
let height = expectedSizeTitle.height+32
let y: CGFloat
if (position == "top") {
y = 40
} else if (position == "center") {
y = (vc.view.bounds.size.height/2) - (height/2)
} else {
y = vc.view.bounds.size.height - height - (height/2)
}
lb.frame = CGRect(
x: ((vc.view.bounds.size.width)/2) - ((expectedSizeTitle.width+32)/2),
y: y,
width: expectedSizeTitle.width+32,
height: height)
lb.padding = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
self.toast = lb
vc.view.addSubview(lb)
UIView.animateKeyframes(withDuration: 0.3, delay: 0, animations: {
self.toast!.alpha = 1.0
}, completion: {(isCompleted) in
UIView.animate(withDuration: 0.3, delay: (Double(duration) / 1000), options: .curveEaseOut, animations: {
self.toast!.alpha = 0.0
}, completion: {(isCompleted) in
self.toast!.removeFromSuperview()
call.success()
})
})
}
}
}