我试图创建一个“弹出视图”,当绑定值不为nil时出现。
我有一个PopupCard
类,它在Content
和一些Value
上通用……
struct PopupCard<Content: View, Value>: View {
@Binding private var data: Value?
private let content: (Value) -> Content
init(data: Binding<Value?>, @ViewBuilder content: @escaping (Value) -> Content) {
self._data = data
self.content = content
}
var body: some View {
Group {
if data != nil {
HStack {
self.content(self.data!)
.padding()
Spacer()
}
.frame(width: UIScreen.main.bounds.width - 40)
.background(
Rectangle()
.fill(Color.yellow)
.shadow(color: Color.black.opacity(0.2), radius: 5, y: 0)
)
.offset(y: self.data == nil ? -100 : 0)
.animation(.default)
}
}
}
}
我还在View
上创建了以下扩展名…
extension View {
func popup<Content: View, Value>(data: Binding<Value?>, @ViewBuilder content: @escaping (Value) -> Content) -> some View {
return ZStack {
self
VStack {
Spacer()
PopupCard(data: data, content: content)
}
}
}
}
除了动画之外,一切都很好。该卡出现和消失按预期的方式,但没有动画。在下面的预览中对此进行了演示……
struct PopupCard_Previews: PreviewProvider {
struct PreviewView: View {
@State var name: String? = "Hello"
var body: some View {
TabView {
Button("Toggle", action: {
self.name = self.name == nil ? "Hello" : nil
})
.popup(data: $name) { string in
Text(string)
}
}
}
}
static var previews: some View {
PreviewView()
}
}
我如何获得这个动画呢?
答案 0 :(得分:1)
这是固定的变体(如果我正确理解了意图)。经过Xcode 11.4 / iOS 13.4的测试
struct PopupCard<Content: View, Value>: View {
@Binding private var data: Value?
private let content: (Value) -> Content
init(data: Binding<Value?>, @ViewBuilder content: @escaping (Value) -> Content) {
self._data = data
self.content = content
}
var body: some View {
Group {
HStack {
if data != nil {
self.content(self.data!).padding()
} else {
Text("")
}
Spacer()
}
.frame(width: UIScreen.main.bounds.width - 40)
.background(
Rectangle()
.fill(Color.yellow)
.shadow(color: Color.black.opacity(0.2), radius: 5, y: 0)
)
.compositingGroup()
.offset(y: self.data == nil ? 100 : 0)
.animation(.default)
}
}
}