笔记笔记
  • Home
  • AI&ML
  • Example
  • Zoo
  • 关于
⌘ K
Swift
组件 Demo
iOS Simulator APP 沙盒地址
SVG
语言
最后更新时间:
Copyright © 2023-2024 | Powered by dumi | GuoDapeng | 冀ICP备20004032号-1 | 冀公网安备 冀公网安备 13024002000293号

TABLE OF CONTENTS

‌
‌
‌
‌

组件 Demo

测试用的 View

import SwiftUI
struct HeroView: View {
var id = 0
var body: some View {
HStack(alignment: .center) {
Spacer()
Text("\(id)")
Spacer()
}
.frame(width: 300, height: 120)
.background(Color.blue.opacity(0.3))
.cornerRadius(8)
.padding(.horizontal, 8)
}
}
#Preview("HeroView Light Mode") {
HeroView()
.preferredColorScheme(.light)
}

ScrollView

每次滚动一页

import SwiftUI
struct ScrollViewDemo: View {
var body: some View {
ScrollView(.horizontal) {
LazyHStack {
ForEach(1...100, id: \.self) { it in
HeroView(id: it)
}
}
}
.scrollTargetBehavior(.paging)
}
}
#Preview("ScrollViewDemo Light Mode") {
ScrollViewDemo()
.preferredColorScheme(.light)
}

每次滚动一个项

import SwiftUI
struct ScrollViewDemo: View {
var body: some View {
ScrollView(.horizontal) {
LazyHStack {
ForEach(1...100, id: \.self) { it in
HeroView(id: it)
}
}
.scrollTargetLayout()
}
.scrollTargetBehavior(.viewAligned)
}
}
#Preview("SearchView Light Mode") {
ScrollViewDemo()
.preferredColorScheme(.light)
}

根据屏幕尺寸适配,每页显示 2 个,每页左右各留 10px 空白

import SwiftUI
struct DemoView: View {
var body: some View {
ScrollView(.horizontal) {
LazyHStack(spacing: 10) {
ForEach(1...20, id: \.self) { it in
GalleryHeroView(id: it)
}
}
.scrollTargetLayout()
}
.contentMargins(.horizontal, 20.0)
.scrollTargetBehavior(.viewAligned)
.scrollIndicators(.never)
}
}
struct GalleryHeroView: View {
// 使用环境变量获取当前视图的水平尺寸类别
@Environment(\.horizontalSizeClass) private var sizeClass
var id: Int
var body: some View {
colorStack
.aspectRatio(16 / 9, contentMode: .fit)
.cornerRadius(20)
.containerRelativeFrame(
[.horizontal], count: sizeClass == .compact ? 1 : 2, spacing: 10
) // 根据尺寸类别调整视图大小和间距
}
@ViewBuilder
private var colorStack: some View {
ZStack {
Color.blue
Text("\(id)")
}
}
}
#Preview("Demo Light Mode") {
DemoView()
.preferredColorScheme(.light)
}