Следующий PickerView использует значение @Binding var: String? , чтобы показать и выбрать какое-то значение.
Должно быть возможно использовать вход и непредвзятые как @Binding вход. Чтобы достичь этого, Pickerview имеет два init s. Один из них принимает дополнительное привязку, и один не необязательный.
Изменения значений использует пользовательский переход анимации
, в то время как это работает нормально, когда PickerView используется внутри обычного представления Swiftui, анимация неопредвостового значения, когда используется внутри uivecontrollor Контейнер.
Как видите, неоптиционное значение в контейнере (нижнее значение в желтом разделе) обновляется без анимации. Все остальные значения правильно анимированы. < /P>
Как это можно решить?struct PickerView: View {
@Binding var value: String?
private var allowNil: Bool = false
// Init with optional Binding input
init(value: Binding) {
self._value = value
allowNil = true
}
// Init with non-optional Binding input
init(value: Binding) {
self._value = Binding(get: {
value.wrappedValue
}, set: { newValue in
if let newValue = newValue {
value.wrappedValue = newValue
}
})
}
var body: some View {
VStack {
Text("Allow Nil: \(allowNil)")
Text(value ?? "-")
.transition(textTransition)
.id(value)
Button("Change Value") {
withAnimation {
value = String(UUID().uuidString.prefix(8))
}
}
}
}
private var textTransition: AnyTransition {
.asymmetric(
insertion: .move(edge: .bottom).combined(with: .opacity),
removal: .move(edge: .top).combined(with: .opacity)
)
}
}
struct PickerPreview: View {
@State var optionalValue: String? = "optional" // OK
@State var value: String = "non optional" // Fails in Container
var body: some View {
VStack {
ContainerView {
VStack(spacing: 20) {
VStack {
Text("Container:")
Text("optional OK, non optional Fails")
}
.font(.headline)
PickerView(value: $optionalValue)
PickerView(value: $value)
}
}
VStack(spacing: 20) {
Text("Both OK")
.font(.headline)
PickerView(value: $optionalValue)
PickerView(value: $value)
}
}
}
}
struct ContainerView: UIViewControllerRepresentable {
let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
func makeUIViewController(context: Context) -> UIViewController {
let containerVC = UIViewController()
containerVC.view.backgroundColor = .yellow
let contentVC = UIHostingController(rootView: self.content)
contentVC.view.backgroundColor = .clear
context.coordinator.contentVC = contentVC
contentVC.willMove(toParent: containerVC)
containerVC.addChild(contentVC)
contentVC.view.translatesAutoresizingMaskIntoConstraints = false
containerVC.view.addSubview(contentVC.view)
NSLayoutConstraint.activate([
contentVC.view.topAnchor.constraint(equalTo: containerVC.view.topAnchor),
contentVC.view.bottomAnchor.constraint(equalTo: containerVC.view.bottomAnchor),
contentVC.view.leadingAnchor.constraint(equalTo: containerVC.view.leadingAnchor),
contentVC.view.trailingAnchor.constraint(equalTo: containerVC.view.trailingAnchor)
])
contentVC.didMove(toParent: containerVC)
return containerVC
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
context.coordinator.contentVC?.rootView = content
}
func makeCoordinator() -> Coordinator {
return Coordinator()
}
class Coordinator: NSObject, UIScrollViewDelegate {
var contentVC: UIHostingController?
}
}
#Preview {
PickerPreview()
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... resentable