Home > database >  swiftUI tabView pagetabviewstyle - button to next is not working
swiftUI tabView pagetabviewstyle - button to next is not working

Time:04-10

import SwiftUI

GuideImageView currentPage mean 1VStack which is in text and images from array from guidelists

struct GuideImageView: View {
@State var currentPage: Int = 0
var body: some View {
VStack{
    TabView(selection: $currentPage){
        ForEach(guidelists){i in
            VStack{
                Text(i.explain)
                Image(i.image)
                    .resizable()
            }
        }
    }.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))  //page처럼 구현   ...을 안보이게함
    
    Button("Next") {
if currentPage == 3 {
                currentPage = 0
                //return
            }else{
                currentPage  = 1
            }            
    }
}
}
}

Struct GuideList

struct GuideList: Identifiable, Hashable{//가이드리스트 구조체, 이미지와 설명넣기
let id = UUID() //UUID = 고유식별자
let image: String
let explain: String
}

let guidelists

let guidelists = [
GuideList(image: "image1",explain: "explain1." ),
GuideList(image: "image2",explain: "explain2." ),
GuideList(image: "image3",explain: "explain3." )
]

GuideImageView_Previews

struct ImageView_Previews: PreviewProvider {
static var previews: some View {
GuideImageView()
}
}

I want to make button to go to next page button seems doesn't work

CodePudding user response:

The reason for this not working is the type mismatch in your models id and the selection var.


Detail:

TabView(selection: $currentPage){
            ForEach(guidelists){i in

these two lines tell the compiler that the id for every element is of type UUID (because GuideList is identifieable and id is of type UUID. Thats fine for itself, but TabView has a selection var of type Int (currentPage is an Int) so it is not working. So changing one of both types to equal the other will solve the problem.


easy example:

Change your code to:

struct GuideList: Identifiable, Hashable{//가이드리스트 구조체, 이미지와 설명넣기
    let id: Int
    let image: String
    let explain: String
}

let guidelists = [
    GuideList(id: 0, image: "image1",explain: "explain1."),
    GuideList(id: 1, image: "image2",explain: "explain2." ),
    GuideList(id: 2, image: "image3",explain: "explain3." )
]
  • Related