英文:
SwiftUI - Banner Transition
问题
我是ShiftUI的新手。
如何在ShiftUI中实现每次切换到下一张图像旋转 'N' 秒的自动横幅过渡?
用于横幅过渡的原生SwiftUI功能。
切换到下一张图像的旋转。我需要底部指示器。
英文:
I am new to ShiftUI.
How can we achieve automation Banner Transition for every move to next image rotation 'N' seconds in ShiftUI ?
Native SwiftUI functionality for banner transition.
Move to next image rotation. I need bottom indicator.
答案1
得分: 0
使用 `Timer` 可以实现这个结果。检查下面的示例代码
import SwiftUI
import Combine
struct ContentView: View {
@StateObject private var viewModel = ContentViewModel()
var body: some View {
TabView(selection: $viewModel.selectedIndex.animation(.spring())) {
ForEach(0 ..< viewModel.colors.count, id: \.self) { index in
viewModel.colors[index]
.tag(index)
}
}
.tabViewStyle(.page(indexDisplayMode: .always))
.animation(viewModel.selectedIndex == 0 ? .none : .default, value: viewModel.selectedIndex)
}
}
final class ContentViewModel: ObservableObject {
@Published var selectedIndex = 0
let colors: [Color] = [
.red,
.blue,
.green,
.yellow,
.orange,
.brown
]
private var timer: Timer?
private var cancellation: AnyCancellable?
init() {
addAutoScrollTimer()
}
func addAutoScrollTimer() {
cancellation = Timer.publish(every: 5, on: .main, in: .default)
.autoconnect()
.sink { [weak self] timer in
self?.handleAutoScroll()
}
}
@objc private func handleAutoScroll() {
selectedIndex = (selectedIndex + 1) % colors.count
}
}
英文:
Use Timer
you can achieve this result. Check below sample code
import SwiftUI
import Combine
struct ContentView: View {
@StateObject private var viewModel = ContentViewModel()
var body: some View {
TabView(selection: $viewModel.selectedIndex.animation(.spring())) {
ForEach(0 ..< viewModel.colors.count, id: \.self) { index in
viewModel.colors[index]
.tag(index)
}
}
.tabViewStyle(.page(indexDisplayMode: .always))
.animation(viewModel.selectedIndex == 0 ? .none : .default, value: viewModel.selectedIndex)
}
}
final class ContentViewModel: ObservableObject {
@Published var selectedIndex = 0
let colors: [Color] = [
.red,
.blue,
.green,
.yellow,
.orange,
.brown
]
private var timer: Timer?
private var cancellation: AnyCancellable?
init() {
addAutoScrollTimer()
}
func addAutoScrollTimer() {
cancellation = Timer.publish(every: 5, on: .main, in: .default)
.autoconnect()
.sink { [weak self] timer in
self?.handleAutoScroll()
}
}
@objc private func handleAutoScroll() {
selectedIndex = (selectedIndex + 1) % colors.count
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论