【发布时间】:2021-01-11 01:32:24
【问题描述】:
我正在尝试创建分页滚动视图 我使用 TabView 来创建它。
这是我的代码
struct TT: Identifiable {
let id = UUID()
var v: String
}
struct TTest: View {
@State var currentIndex = 0
@State var data = [
TT(v: "0")
]
var body: some View {
VStack {
SwiftUI.TabView(selection: $currentIndex) {
ForEach(data.indexed(), id: \.1.id) { index, value in
TTestConsomer(data: $data[index]).tag(index)
}
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
Spacer()
HStack {
Image(systemName: "plus")
.resizable()
.frame(width: 50, height: 50)
.onTapGesture(perform: add)
Image(systemName: "minus")
.resizable()
.frame(width: 50, height: 5)
.onTapGesture(perform: delete)
}
Text("\(currentIndex + 1)/\(data.count)")
}
}
func add() {
data.append(TT(v: "\(data.count)") )
}
func delete() {
data.remove(at: currentIndex)
}
}
struct TTestConsomer: View {
@Binding var data: TT
var body: some View {
Text(data.v)
.padding(30)
.border(Color.black)
}
}
// You also need this extension
extension RandomAccessCollection {
func indexed() -> IndexedCollection<Self> {
IndexedCollection(base: self)
}
}
struct IndexedCollection<Base: RandomAccessCollection>: RandomAccessCollection {
typealias Index = Base.Index
typealias Element = (index: Index, element: Base.Element)
let base: Base
var startIndex: Index { base.startIndex }
var endIndex: Index { base.endIndex }
func index(after i: Index) -> Index {
base.index(after: i)
}
func index(before i: Index) -> Index {
base.index(before: i)
}
func index(_ i: Index, offsetBy distance: Int) -> Index {
base.index(i, offsetBy: distance)
}
subscript(position: Index) -> Element {
(index: position, element: base[position])
}
}
当我单击 + 按钮时,我可以添加更多选项卡。 但是当我点击删除按钮时,我的应用程序崩溃了。 这里有什么问题?代码似乎没有什么问题。
【问题讨论】:
-
这是否回答了您的问题stackoverflow.com/a/63500070/12299030?
-
我无法让它工作。
-
我最终只使用了 Apple 的示例代码,它将 UIKit 代码包装到 Swift 包装器中。
标签: swiftui