SizeTextField.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //
  2. // Copyright © 2022 osy. All rights reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. import SwiftUI
  17. struct SizeTextField: View {
  18. @Binding var sizeMib: Int
  19. @State private var isGiB: Bool = true
  20. private let mibToGib = 1024
  21. let minSizeMib: Int
  22. init(_ sizeMib: Binding<Int>, minSizeMib: Int = 1) {
  23. _sizeMib = sizeMib
  24. self.minSizeMib = minSizeMib
  25. }
  26. var body: some View {
  27. HStack {
  28. NumberTextField("Size", number: Binding<Int>(get: {
  29. convertToDisplay(fromSizeMib: sizeMib)
  30. }, set: {
  31. sizeMib = convertToMib(fromSize: $0)
  32. }), onEditingChanged: validateSize)
  33. .multilineTextAlignment(.trailing)
  34. .help("The amount of storage to allocate for this image. Ignored if importing an image. If this is a raw image, then an empty file of this size will be stored with the VM. Otherwise, the disk image will dynamically expand up to this size.")
  35. Button(action: { isGiB.toggle() }, label: {
  36. Group {
  37. if isGiB {
  38. Text("GiB")
  39. } else {
  40. Text("MiB")
  41. }
  42. }.foregroundColor(.blue)
  43. }).buttonStyle(.plain)
  44. }
  45. }
  46. private func validateSize(editing: Bool) {
  47. guard !editing else {
  48. return
  49. }
  50. if sizeMib < minSizeMib {
  51. sizeMib = minSizeMib
  52. }
  53. }
  54. private func convertToMib(fromSize size: Int) -> Int {
  55. if isGiB {
  56. return size * mibToGib
  57. } else {
  58. return size
  59. }
  60. }
  61. private func convertToDisplay(fromSizeMib sizeMib: Int) -> Int {
  62. if isGiB {
  63. return sizeMib / mibToGib
  64. } else {
  65. return sizeMib
  66. }
  67. }
  68. }
  69. struct SizeTextField_Previews: PreviewProvider {
  70. static var previews: some View {
  71. SizeTextField(.constant(100))
  72. }
  73. }