当我试图添加一个加号按钮时,它重叠在列表的两行上。该代码适用于以下情况:1(当视图出现时,2(从上到下滚动(每次(。然而,当我从列表的底部滚动到顶部时,代码无法正常工作。从下到上滚动后,下一行与加号图像的某个部分重叠。
此外,当视图出现在屏幕上时,我试图通过更改图像的前景色来刷新加号图像。但是,它没有起作用。在这里,我正在切换Card模型的needRefresh变量来刷新加号图像。
要求
struct Card: Identifiable {
var cardNum = 0
var id = UUID()
var needRefresh: Bool = false
init(cardNum: Int) {
self.cardNum = cardNum
}
}
class CardModel: ObservableObject {
@Published var cards = [Card]()
init() {
for val in (1...10) {
let card = Card(cardNum: val)
cards.append(card)
}
}
}
struct ContentView: View {
@StateObject var cardModel = CardModel()
@State var refreshStatus = false
var body: some View {
NavigationView {
List($cardModel.cards) { $card in
CardViewRow(card: $card)
}
.navigationTitle("List")
.navigationBarTitleDisplayMode(.inline)
}
}
}
struct CardViewRow: View {
@Binding var card: Card
var body: some View {
ZStack(alignment: .bottom){
CardView()
Image(systemName: "plus.app.fill")
.font(.system(size: 40.0))
.offset(y: 25)
.foregroundColor(card.needRefresh ? .blue : .red)
.onAppear {
card.needRefresh.toggle()
}
}
}
}
struct CardView: View {
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 25, style: .continuous)
.fill(.white)
.shadow(radius: 10)
VStack {
Text("Question")
.font(.largeTitle)
.foregroundColor(.black)
Text("Answer")
.font(.title)
.foregroundColor(.gray)
}
.padding(20)
.multilineTextAlignment(.center)
}
.frame(width: UIScreen.main.bounds.size.width - 40, height: 150)
}
}
我认为使用列表会很棘手,因为它"作物";列表单元格。但对于ScrollView
和LazyVStack
:,它也可以这样工作
struct ContentView: View {
@ObservedObject var cardVM = CardVM()
@State var refreshStatus = false
var body: some View {
NavigationView {
ScrollView {
LazyVStack(spacing: -15) {
ForEach(cardVM.cardList, id: .id) { card in
CardViewRow(card: card)
}
}
}
.listStyle(.plain)
.navigationTitle("List")
.navigationBarTitleDisplayMode(.inline)
}
}
}
struct CardViewRow: View {
@ObservedObject var card: Card
var body: some View {
CardView()
Image(systemName: "plus.app.fill")
.font(.system(size: 40.0))
.offset(y: 0)
.foregroundColor(card.needRefresh ? .blue : .red)
.zIndex(1)
.onAppear {
card.needRefresh.toggle()
}
}
}