美文网首页
SwiftUI-实现横向滑动视图

SwiftUI-实现横向滑动视图

作者: Augs | 来源:发表于2019-12-07 16:51 被阅读0次

定义数据结构体:

struct Box {
    var id: Int
    let title, imageUrl: String
}

定义横向滑动单元格:

import SwiftUI

struct BoxView: View {
    
    let box: Box
    
    var body: some View {
        VStack {
            Image("\(box.imageUrl)")
                .resizable()
                .cornerRadius(12)
                .frame(width: 80, height: 80)
            Text("\(box.title)")
                .font(.subheadline)
                .fontWeight(.bold)
        }
    }
}

#if DEBUG
struct BoxView_Previews: PreviewProvider {
    static var previews: some View {
        BoxView(box: Box(id: 4, title: "SwiftUI", imageUrl: "4"))
    }
}
#endif

效果:


截屏2019-12-0716.42.59.png

定义展示页面:

import SwiftUI

struct BoxContentView: View {
    
    let boxes: [Box] = [
        Box(id: 0, title: "Autumn", imageUrl: "0"),
        Box(id: 1, title: "Natural", imageUrl: "1"),
        Box(id: 2, title: "Jiuzhaigou", imageUrl: "2"),
        Box(id: 3, title: "Mountain", imageUrl: "3"),
        Box(id: 4, title: "Lake", imageUrl: "4"),
    ]
    
    var body: some View {
        NavigationView {
            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(boxes, id: \.id) { box in
                        BoxView(box: box)
                    }
                }
                Spacer()
            }.padding(20)
                
            .navigationBarTitle(Text("Beautiful Scenery!"))
        }
    }
}

#if DEBUG
struct BoxContentView_Previews: PreviewProvider {
    static var previews: some View {
        BoxContentView()
    }
}
#endif

最终效果:


2019-12-07 16.36.15.gif

相关文章

网友评论

      本文标题:SwiftUI-实现横向滑动视图

      本文链接:https://www.haomeiwen.com/subject/dsmugctx.html