我想制作一個帶有錯誤訊息的小視圖:
enum SomeStates {
case good
case bad
var errorMessage: String? {
switch self {
case .good: return nil
case .bad: return "a sad error has occured"
}
}
}
struct ErrorForState: View {
@State var errorMessage: String?
@Binding var state: SomeStates
var body: some View {
return Group {
if let message = errorMessage {
Text(message)
.foregroundColor(Color(hex: 0x874b4b))
.padding(15)
.background(Color(hex: 0xffefef))
.cornerRadius(10)
.transition(.scale)
}
}
.onChange(of: state) { _ in
withAnimation(.spring()) {
errorMessage = state.errorMessage
}
}
}
}
這行得通!我的視圖檢測系結何時更改并在塊中設定errorMessage自身。withAnimation
但我不喜歡withAnimation在這里使用,因為它非常冗長,需要我有一個額外的狀態變數errorMessage,而且我不喜歡它如何解耦關于影片 /from/ 被影片的事物和 /to/ 事物觸發的細節影片。我原本想做這樣的事情:
struct ErrorForState: View {
@Binding var state: SomeStates
var body: some View {
return Group {
if let message = state.errorMessage {
Text(message)
.foregroundColor(Color(hex: 0x874b4b))
.padding(15)
.background(Color(hex: 0xffefef))
.cornerRadius(10)
.transition(.scale)
.animation(Animation.easeInOut(duration: 1.0), value: state.errorMessage)
}
}
}
}
但是這不起作用,而是立即出現/消失。事實上,我.animation在 iOS 15 上所做的每一個解決方案嘗試似乎都不起作用。
我懷疑我不明白它是如何.animation作業的——也許我把它放在上面的錯誤位置(也許是因為我的Text視圖是有條件地呈現的?)。當附加到任何一個時,它似乎也不起作用Group。
uj5u.com熱心網友回復:
這是您的一種方法:
在 if 或 if let 中使用 Animation 不會給您帶來任何好處或結果!因為影片隨著值的變化而起作用,當你把它放在 if 里面時,它剛剛被初始化,除非你確定你可以用 group 替換它,否則不要使用 group,而是使用 VStack。
struct ErrorForState: View {
@Binding var state: SomeStates
var body: some View {
return VStack(spacing: .zero) {
if let message = state.errorMessage {
Text(message)
.foregroundColor(Color(hex: 0x874b4b))
.padding(15)
.background(Color(hex: 0xffefef))
.cornerRadius(10)
.transition(.scale)
}
}
.animation(Animation.easeInOut(duration: 1.0), value: state.errorMessage)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/488243.html
下一篇:基于列值組合行
