SwiftUI listRowBackground 无法制作动画?



我试图模仿一个单元格的正常UITableView行为,当你点击它,然后淡出。我已经很接近了,除了:

  • .background()不会填充整个列表单元格,它只适合内容周围。
  • .listRowBackground()填充单元格,但它不动画。

是否有一种方法来动画列表行背景?

下面是完整上下文的来源。如前所述,因为listRowBackground不动,你永远不会看到背景的变化。如果您将其更改为background,则它会按预期动画,但不会填充单元格。

struct Profile {
let name: String
var selected: Bool
var hilited: Bool = false
}
extension Profile: Identifiable {
var id: String { name }
}
struct ProfilesPicker: View {
@State var profiles: [Profile]
var body: some View {
List {
ForEach(0..<profiles.count) { index in
let profile = profiles[index]
CheckCell(name: profile.name, checked: profile.selected)
// using .background() gets a proper fade but doesn't fill the cell
.listRowBackground(Color(profile.hilited ? UIColor.systemFill : UIColor.systemBackground))
.onTapGesture {
profiles[index].hilited = true
withAnimation(.easeIn) {
profiles[index].hilited = false
profiles[index].selected.toggle()
}
}
}
}
}
}
struct CheckCell: View {
let name: String
let checked: Bool
var body: some View {
HStack {
Text(name)
Spacer()
if checked {
Image(systemName: "checkmark")
}
}
.contentShape(Rectangle())
}
}

使用延迟并为listRowBackground添加动画

struct ProfilesPicker: View {
@State var profiles: [Profile]

var body: some View {
List {
ForEach(0..<profiles.count) { index in
let profile = profiles[index]

CheckCell(name: profile.name, checked: profile.selected)
.onTapGesture {
profiles[index].hilited = true

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { //<==Here
profiles[index].hilited = false
profiles[index].selected.toggle()
}
}
.animation(.default)
.listRowBackground(Color(profile.hilited ? UIColor.systemFill : UIColor.systemBackground).animation(.easeInOut)) //<==Here
}
}
}
}

最新更新