У меня есть небольшая проблема с переходной анимацией Swiftui. Учебное пособие создает приложение, похожее на Tinder, которое сжимает изображения слева и вправо. Если вы проведите, пройдите порог, то изображение удаляется из Hieraquie. Удаление изображения тригеров анимация перехода. Проблема в том, что когда я удаляю первую Imagem, анимация не происходит, но с второго изображения анимация работает очень хорошо. Я не знаю, что происходит. Я делаю то же самое со следующими Имимами, и анимация работает нормально:
< /p>
И здесь я замедлил анимацию на симуляторе. Вы можете видеть, что первая анимация работает нормально, когда анимация замедляется:
< /p>
Вот код, который я использую: < /p>
import SwiftUI
struct ContentView: View {
@GestureState private var dragState: DragState = .inactive
@State private var zIndexCounter: Double = 1_000_000_000.0
@State private var lastIndex: Int = 1
@State private var cardView: [CardView] = Array(trips[0.. self.dragThreshold {
self.removalTransition = .trailingBottom
}
}
.onEnded { value in
guard case .second(true, let drag?) = value,
drag.translation.width < -dragThreshold || drag.translation.width > dragThreshold
else {
return
}
moveCard()
}
)
}
}
Spacer(minLength: 20)
BottomBar { } likeAction: { } bookItNowAction: { }
.opacity(dragState.isDragging ? 0.0 : 1.0)
.animation(.default)
}
}
private func isTopCard(_ trip: CardView) -> Bool {
guard let index = cardView.firstIndex(where: { $0.id == trip.id }) else { return false }
return index == 0
}
private func zIndex(for trip: CardView) -> Double {
let idx = isTopCard(trip) ? zIndexCounter : zIndexCounter - 1
return idx
}
private func offset(for trip: CardView) -> CGSize {
return isTopCard(trip)
? CGSize(width: dragState.tranlation.width, height: dragState.tranlation.height)
: .zero
}
private func scaleEffect(for trip: CardView) -> CGFloat {
if isTopCard(trip) {
return dragState.isDragging ? 0.95 : 1.0
}
return 1.0
}
private func rotationEffect(for trip: CardView) -> Angle {
return isTopCard(trip) ? .degrees(Double(dragState.tranlation.width / 10)) : .zero
}
private func opacity(for trip: CardView, withXMark isXMark: Bool) -> Double {
if isTopCard(trip) {
if isXMark {
return dragState.tranlation.width < -dragThreshold ? 1.0 : 0
}
return dragState.tranlation.width > dragThreshold ? 1.0 : 0
}
return 0
}
private func moveCard() {
cardView.removeFirst()
lastIndex += 1
zIndexCounter -= 1
cardView.append(CardView(trip: trips[lastIndex % trips.count]))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
enum DragState: Equatable {
case inactive
case pressing
case dragging(translation: CGSize)
var tranlation: CGSize {
switch self {
case .inactive, .pressing:
return .zero
case let .dragging(translation):
return translation
}
}
var isDragging: Bool {
switch self {
case .dragging:
return true
case .pressing, .inactive:
return false
}
}
var isPressing: Bool {
switch self {
case .dragging, .pressing:
return true
case .inactive:
return false
}
}
static func == (lhs: Self, rhs: Self) -> Bool {
var result = false
switch (lhs, rhs) {
case (.inactive, .inactive), (.pressing, pressing):
result = true
case let (.dragging(translation1), .dragging(translation2)):
result = translation1 == translation2
default:
result = false
}
return result
}
}
extension AnyTransition {
static var trailingBottom: AnyTransition {
AnyTransition.asymmetric(
insertion: .identity,
removal: AnyTransition
.move(edge: .trailing)
.combined(with: .move(edge: .bottom))
)
}
static var leadingBottom: AnyTransition {
AnyTransition.asymmetric(
insertion: .identity,
removal: AnyTransition
.move(edge: .leading)
.combined(with: .move(edge: .bottom))
)
}
}
struct CardView: View, Identifiable {
let id = UUID()
let trip: Trip
var body: some View {
Image(trip.image)
.resizable()
.scaledToFill()
.frame(minWidth: 0, maxWidth: .infinity)
.cornerRadius(10)
.overlay(
Text(trip.destination)
.font(.system(.headline, design: .rounded))
.fontWeight(.bold)
.foregroundColor(.primary)
.padding(.vertical, 10)
.padding(.horizontal, 30)
.background(Color.white)
.cornerRadius(5)
.padding(.bottom),
alignment: .bottom)
}
}
struct Trip: Identifiable {
let id = UUID()
var destination: String
var image: String
}
var trips = [ Trip(destination: "Yosemite, USA", image: "yosemite-usa"),
Trip(destination: "Venice, Italy", image: "venice-italy"),
Trip(destination: "Hong Kong", image: "hong-kong"),
Trip(destination: "Barcelona, Spain", image: "barcelona-spain"),
Trip(destination: "Braies, Italy", image: "braies-italy"),
Trip(destination: "Kanangra, Australia", image: "kanangra-australia"),
Trip(destination: "Mount Currie, Canada", image: "mount-currie-canada"),
Trip(destination: "Ohrid, Macedonia", image: "ohrid-macedonia"),
Trip(destination: "Oia, Greece", image: "oia-greece"),
Trip(destination: "Palawan, Philippines", image: "palawan-philippines"),
Trip(destination: "Salerno, Italy", image: "salerno-italy"),
Trip(destination: "Tokyo, Japan", image: "tokyo-japan"),
Trip(destination: "West Vancouver, Canada", image: "west-vancouver-canada"),
Trip(destination: "Singapore", image: "garden-by-bay-singapore"),
Trip(destination: "Perhentian Islands, Malaysia", image: "perhentian-islands-malaysia")
]
struct BottomBar: View {
let discardAction: () -> Void
let likeAction: () -> Void
let bookItNowAction: () -> Void
var body: some View {
HStack {
Button(action: discardAction) {
Image(systemName: "xmark")
.font(.title)
}
Spacer()
Button(action: bookItNowAction) {
Text("BOOK IT NOW")
.font(.system(.subheadline, design: .rounded))
.fontWeight(.bold)
.padding(.horizontal, 35)
.padding(.vertical, 15)
.foregroundColor(.white)
.background(Color.primary)
.cornerRadius(10)
}
Spacer()
Button(action: likeAction) {
Image(systemName: "heart")
.font(.title)
}
}
.foregroundColor(.primary)
.padding()
}
}
struct TopBar: View {
let menuAction: () -> Void
let likeAction: () -> Void
var body: some View {
HStack {
Button(action: menuAction) {
Image(systemName: "line.horizontal.3")
.font(.title)
}
Spacer()
Image(systemName: "mappin.and.ellipse")
.font(.largeTitle)
Spacer()
Button(action: likeAction) {
Image(systemName: "heart.circle.fill")
.font(.title)
}
}
.padding()
.foregroundColor(.primary)
}
}
< /code>
Любое Sugestion?
Спасибо < /p>
Подробнее здесь: https://stackoverflow.com/questions/794 ... first-time
Переходная анимация Swiftui не работает в первый раз ⇐ IOS
Программируем под IOS
-
Anonymous
1739279713
Anonymous
У меня есть небольшая проблема с переходной анимацией Swiftui. Учебное пособие создает приложение, похожее на Tinder, которое сжимает изображения слева и вправо. Если вы проведите, пройдите порог, то изображение удаляется из Hieraquie. Удаление изображения тригеров анимация перехода. Проблема в том, что когда я удаляю первую Imagem, анимация не происходит, но с второго изображения анимация работает очень хорошо. Я не знаю, что происходит. Я делаю то же самое со следующими Имимами, и анимация работает нормально:
< /p>
И здесь я замедлил анимацию на симуляторе. Вы можете видеть, что первая анимация работает нормально, когда анимация замедляется:
< /p>
Вот код, который я использую: < /p>
import SwiftUI
struct ContentView: View {
@GestureState private var dragState: DragState = .inactive
@State private var zIndexCounter: Double = 1_000_000_000.0
@State private var lastIndex: Int = 1
@State private var cardView: [CardView] = Array(trips[0.. self.dragThreshold {
self.removalTransition = .trailingBottom
}
}
.onEnded { value in
guard case .second(true, let drag?) = value,
drag.translation.width < -dragThreshold || drag.translation.width > dragThreshold
else {
return
}
moveCard()
}
)
}
}
Spacer(minLength: 20)
BottomBar { } likeAction: { } bookItNowAction: { }
.opacity(dragState.isDragging ? 0.0 : 1.0)
.animation(.default)
}
}
private func isTopCard(_ trip: CardView) -> Bool {
guard let index = cardView.firstIndex(where: { $0.id == trip.id }) else { return false }
return index == 0
}
private func zIndex(for trip: CardView) -> Double {
let idx = isTopCard(trip) ? zIndexCounter : zIndexCounter - 1
return idx
}
private func offset(for trip: CardView) -> CGSize {
return isTopCard(trip)
? CGSize(width: dragState.tranlation.width, height: dragState.tranlation.height)
: .zero
}
private func scaleEffect(for trip: CardView) -> CGFloat {
if isTopCard(trip) {
return dragState.isDragging ? 0.95 : 1.0
}
return 1.0
}
private func rotationEffect(for trip: CardView) -> Angle {
return isTopCard(trip) ? .degrees(Double(dragState.tranlation.width / 10)) : .zero
}
private func opacity(for trip: CardView, withXMark isXMark: Bool) -> Double {
if isTopCard(trip) {
if isXMark {
return dragState.tranlation.width < -dragThreshold ? 1.0 : 0
}
return dragState.tranlation.width > dragThreshold ? 1.0 : 0
}
return 0
}
private func moveCard() {
cardView.removeFirst()
lastIndex += 1
zIndexCounter -= 1
cardView.append(CardView(trip: trips[lastIndex % trips.count]))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
enum DragState: Equatable {
case inactive
case pressing
case dragging(translation: CGSize)
var tranlation: CGSize {
switch self {
case .inactive, .pressing:
return .zero
case let .dragging(translation):
return translation
}
}
var isDragging: Bool {
switch self {
case .dragging:
return true
case .pressing, .inactive:
return false
}
}
var isPressing: Bool {
switch self {
case .dragging, .pressing:
return true
case .inactive:
return false
}
}
static func == (lhs: Self, rhs: Self) -> Bool {
var result = false
switch (lhs, rhs) {
case (.inactive, .inactive), (.pressing, pressing):
result = true
case let (.dragging(translation1), .dragging(translation2)):
result = translation1 == translation2
default:
result = false
}
return result
}
}
extension AnyTransition {
static var trailingBottom: AnyTransition {
AnyTransition.asymmetric(
insertion: .identity,
removal: AnyTransition
.move(edge: .trailing)
.combined(with: .move(edge: .bottom))
)
}
static var leadingBottom: AnyTransition {
AnyTransition.asymmetric(
insertion: .identity,
removal: AnyTransition
.move(edge: .leading)
.combined(with: .move(edge: .bottom))
)
}
}
struct CardView: View, Identifiable {
let id = UUID()
let trip: Trip
var body: some View {
Image(trip.image)
.resizable()
.scaledToFill()
.frame(minWidth: 0, maxWidth: .infinity)
.cornerRadius(10)
.overlay(
Text(trip.destination)
.font(.system(.headline, design: .rounded))
.fontWeight(.bold)
.foregroundColor(.primary)
.padding(.vertical, 10)
.padding(.horizontal, 30)
.background(Color.white)
.cornerRadius(5)
.padding(.bottom),
alignment: .bottom)
}
}
struct Trip: Identifiable {
let id = UUID()
var destination: String
var image: String
}
var trips = [ Trip(destination: "Yosemite, USA", image: "yosemite-usa"),
Trip(destination: "Venice, Italy", image: "venice-italy"),
Trip(destination: "Hong Kong", image: "hong-kong"),
Trip(destination: "Barcelona, Spain", image: "barcelona-spain"),
Trip(destination: "Braies, Italy", image: "braies-italy"),
Trip(destination: "Kanangra, Australia", image: "kanangra-australia"),
Trip(destination: "Mount Currie, Canada", image: "mount-currie-canada"),
Trip(destination: "Ohrid, Macedonia", image: "ohrid-macedonia"),
Trip(destination: "Oia, Greece", image: "oia-greece"),
Trip(destination: "Palawan, Philippines", image: "palawan-philippines"),
Trip(destination: "Salerno, Italy", image: "salerno-italy"),
Trip(destination: "Tokyo, Japan", image: "tokyo-japan"),
Trip(destination: "West Vancouver, Canada", image: "west-vancouver-canada"),
Trip(destination: "Singapore", image: "garden-by-bay-singapore"),
Trip(destination: "Perhentian Islands, Malaysia", image: "perhentian-islands-malaysia")
]
struct BottomBar: View {
let discardAction: () -> Void
let likeAction: () -> Void
let bookItNowAction: () -> Void
var body: some View {
HStack {
Button(action: discardAction) {
Image(systemName: "xmark")
.font(.title)
}
Spacer()
Button(action: bookItNowAction) {
Text("BOOK IT NOW")
.font(.system(.subheadline, design: .rounded))
.fontWeight(.bold)
.padding(.horizontal, 35)
.padding(.vertical, 15)
.foregroundColor(.white)
.background(Color.primary)
.cornerRadius(10)
}
Spacer()
Button(action: likeAction) {
Image(systemName: "heart")
.font(.title)
}
}
.foregroundColor(.primary)
.padding()
}
}
struct TopBar: View {
let menuAction: () -> Void
let likeAction: () -> Void
var body: some View {
HStack {
Button(action: menuAction) {
Image(systemName: "line.horizontal.3")
.font(.title)
}
Spacer()
Image(systemName: "mappin.and.ellipse")
.font(.largeTitle)
Spacer()
Button(action: likeAction) {
Image(systemName: "heart.circle.fill")
.font(.title)
}
}
.padding()
.foregroundColor(.primary)
}
}
< /code>
Любое Sugestion?
Спасибо < /p>
Подробнее здесь: [url]https://stackoverflow.com/questions/79428659/swiftuis-transition-animation-does-not-run-for-the-first-time[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия