在 TabView 中获取当前索引(PageTabViewStyle)

时间:2021-03-22 18:46:27

标签: swiftui tabview pagetabviewstyle

我无法添加 gif。我上传了 YouTube。链接here.

当 Tabview 滑动时,我想在下面的 imageView 中显示该图像。

注意:当我尝试使用模型时,我的代码不起作用。这就是为什么我编辑了我的问题。

主视图

struct MainView: View {
    @State var selected: Movie = Movie(title: "", description: "", poster: "", thumbImage: [], video: "", positiveRate: 0, negativeRate: 0)
    var body: some View {
        ZStack {
            Image(selected.poster)
                .resizable()
                .overlay(Blur().edgesIgnoringSafeArea(.all))
            VStack {
                TabView(selection: $selected) {
                    ForEach(movieList, id: \.id) { item in
                        MovieCell(movie: item)
                    }
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
                .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
                
            }
            
        }
    }
}

模型

struct Movie: Identifiable, Hashable {
    var id = UUID()
    var title: String
    var description: String
    var poster: String
    var thumbImage: [String]
    var video: String
    var positiveRate: Int
    var negativeRate: Int
}

示例数据

let movieList = [
    Movie(title: "Minyonlar 2", description: "In the heart of the 1970s, amidst a flurry of feathered hair and flared jeans, Gru (Steve Carell) is growing up in the suburbs. A fanboy of a supervillain supergroup known as the Vicious 6, Gru hatches a plan to become evil enough to join them. Luckily, he gets some mayhem-making back-up from his loyal followers, the Minions. Together, Kevin, Stuart, Bob, and Otto - a new Minion sporting braces and a desperate need to please - deploy their skills as they and Gru build their first lair, experiment with their first weapons, and pull off their first missions. When the Vicious 6 oust their leader, legendary fighter Wild Knuckles (Alan Arkin), Gru interviews to become their newest member. It doesn't go well (to say the least), and only gets worse after Gru outsmarts them and suddenly finds himself the mortal enemy of the apex of evil. On the run, Gru will turn to an unlikely source for guidance, Wild Knuckles, and discover that even bad guys need a little help from their friends. Written by Universal Pictures", poster: "2", thumbImage: ["minions/m1","minions/m2","minions/m3"], video: Bundle.main.path(forResource: "minyonlar", ofType: "mp4")!, positiveRate: 150, negativeRate: 5, categoryType: .animation),
    Movie(title: "Hiçkimse", description: "Emmy winner Bob Odenkirk (Better Call Saul, The Post, Nebraska) stars as Hutch Mansell, an underestimated and overlooked dad and husband, taking life's indignities on the chin and never pushing back. A nobody. When two thieves break into his suburban home one night, Hutch declines to defend himself or his family, hoping to prevent serious violence. His teenage son, Blake (Gage Munroe, The Shack), is disappointed in him and his wife, Becca (Connie Nielsen, Wonder Woman), seems to pull only further away. The aftermath of the incident strikes a match to Hutch's long-simmering rage, triggering dormant instincts and propelling him on a brutal path that will surface dark secrets and lethal skills. In a barrage of fists, gunfire and squealing tires, Hutch must save his family from a dangerous adversary (famed Russian actor Aleksey Serebryakov, Amazon's McMafia)-and ensure that he will never be underestimated as a nobody again. Written by Universal Pictures", poster: "1", thumbImage: ["hickimse/h1","hickimse/h2","hickimse/h3"], video: Bundle.main.path(forResource: "hickimse", ofType: "mp4")!, positiveRate: 100, negativeRate: 250, categoryType: .action),
    Movie(title: "Six Minutes of Midnight", description: "Summer 1939. Influential families in Nazi Germany have sent their daughters to a finishing school in an English seaside town to learn the language and be ambassadors for a future looking National Socialist. A teacher there sees what is coming and is trying to raise the alarm. But the authorities believe he is the problem. Written by Andy Evans", poster: "3", thumbImage: ["sixminutes/s1"], video: Bundle.main.path(forResource: "sixMinutes", ofType: "mp4")!, positiveRate: 80, negativeRate: 60, categoryType: .war)
    
]

3 个答案:

答案 0 :(得分:1)

只需在图像中指定选择,例如

    Image(selected)         // << here !1
        .resizable()
        .frame(width: 150, height: 200)

使用 Xcode 12.4 / iOS 14.4 对复制代码进行测试

答案 1 :(得分:0)

您需要将 tag 添加到您的 TabView 项目。请注意,这些标签的类型必须为 Movie - 与 selected 属性的类型相同。

struct MainView: View {
    @State var selected: Movie = movieList[0] // set the selection to the first item
    var body: some View {
        ZStack {
            Image(selected.poster)
                .resizable()
                .overlay(Blur().edgesIgnoringSafeArea(.all))
            VStack {
                TabView(selection: $selected) {
                    ForEach(movieList, id: \.id) { item in
                        MovieCell(movie: item)
                            .tag(item) // `tag` items here
                    }
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
                .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
            }
        }
    }
}

答案 2 :(得分:0)

更改您的代码以使用索引而不是对象。

struct MainView: View {
    @State var selectedIdx: Int = 0
    var body: some View {
        ZStack {
            Image(movieList[selectedIdx].poster)
                .resizable()
                //.overlay(Blur().edgesIgnoringSafeArea(.all)) //Code not provided
            VStack {
                TabView(selection: $selectedIdx) {
                    ForEach(0..<movieList.count, id: \.self) { idx in
                        Text(movieList[idx].title).tag(idx)//Don't forget this
                    }
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
                .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
                
            }
            
        }
    }
}