而不是在文本陣列下有一組影像,我希望有一個陣列交替使用影像或文本,具體取決于我按下按鈕文本還是按鈕圖片。
這是我嘗試過的:
struct HistoryPicture: Identifiable {let id = UUID ()
var picture: Image?}
struct HistoryText: Identifiable {let id = UUID ()
var text: String?}
struct ContentView: View {
@State var archivePicture: [HistoryPicture] = []
@State var archiveText: [HistoryText] = []
var body: some View {ScrollView{
VStack(spacing:20){
ForEach(self.archiveText) { item in
Text("<text>")
}
ForEach(self.archivePicture) { item in
Image("simpson")
}
// Button Text
HStack{
Button {var newHistory = HistoryText()
newHistory.text = "<text>"
self.archiveText.append(newHistory)
} label: { Circle()
.fill(Color.black)
.frame(width: 70, height: 70)} }
// Button Picture
HStack{
Button {var newHistoryPicture = HistoryPicture()
newHistoryPicture.picture = Image("simpson")
self.archivePicture.append(newHistoryPicture)
} label: { Circle()
.fill(Color.red)
.frame(width: 70, height: 70)
}} }} }}
uj5u.com熱心網友回復:
使用此解決方案,您可以按按鈕按下的順序獲得結果。為此,您只需要一個 ForEach 和一個結構。如果您想要 ForEach 中更復雜的視圖,我建議您使用協議或繼承。
struct HistoryItem: Identifiable {
let id = UUID()
var text: String?
var imageName: String?
}
struct ContentView: View {
@State var items = [HistoryItem]()
var body: some View {
ScrollView {
VStack(spacing: 20){
ForEach(items) { item in
if let text = item.text {
Text(text)
} else if let imageName = item.imageName {
Image(imageName)
}
}
HStack {
Button {
let newItem = HistoryItem(text: "<text>")
items.append(newItem)
} label: {
Circle()
.fill(Color.black)
.frame(width: 70, height: 70)
}
Button {
let newItem = HistoryItem(imageName: "simpson")
items.append(newItem)
} label: {
Circle()
.fill(Color.red)
.frame(width: 70, height: 70)
}
}
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/512721.html
標籤:数组细绳图片循环迅捷
下一篇:用保持大小的影像填充行內容
