Я пытаюсь анимировать расширение строки внутри списка, когда пользователь нажимает на значок заметки. Заворачиваю изменение состояния в withAnimation, но заметка появляется с плохой анимацией и строки ниже без анимации продавливаются вниз (резко "подпрыгивают"). Как правильно анимировать расширение, включая сдвиг макета строк ниже?
Вот минимальный рабочий пример, воспроизводящий такое поведение (скопируйте в новый проект SwiftUI и запустите):
import SwiftUI
@main
struct ExpansionApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct HistoryItem: Identifiable, Hashable {
let id: UUID
let title: String
let note: String?
}
// MARK: - View
struct ContentView: View {
// Keeps the sample aligned with the real screen behavior for note expansion.
@State private var expandedNoteItems: Set = []
private let items: [HistoryItem] = [
HistoryItem(id: UUID(), title: "Client A - Morning shift", note: "Short note for entry 1."),
HistoryItem(id: UUID(), title: "Client B - Field visit", note: "Longer note for entry 2 so the row expands more than the others."),
HistoryItem(id: UUID(), title: "Client C - Training", note: nil),
HistoryItem(id: UUID(), title: "Client D - Support", note: "Another note for entry 4."),
HistoryItem(id: UUID(), title: "Client E - Wrap up", note: "Final note for entry 5.")
]
var body: some View {
NavigationStack {
List {
ForEach(items, id: \.id) { item in
VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 12) {
Text(item.title)
.font(.headline)
Spacer()
if item.note != nil {
Button {
toggleNote(for: item.id)
} label: {
Image(systemName: "note.text")
.imageScale(.medium)
}
.buttonStyle(.plain)
}
}
if let note = item.note, expandedNoteItems.contains(item.id) {
Text(note)
.font(.subheadline)
.foregroundStyle(.secondary)
.padding(10)
.background(Color(.secondarySystemBackground))
.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
}
}
.padding(.vertical, 8)
}
}
.listStyle(.plain)
.navigationTitle("History")
}
}
private func toggleNote(for id: UUID) {
withAnimation {
if expandedNoteItems.contains(id) {
expandedNoteItems.remove(id)
} else {
expandedNoteItems.insert(id)
}
}
}
}
// MARK: - Preview
#Preview {
ContentView()
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... p-abruptly
Расширение строк списка SwiftUI не анимируется плавно; предметы ниже резко подпрыгивают ⇐ IOS
Программируем под IOS
1769552021
Anonymous
Я пытаюсь анимировать расширение строки внутри списка, когда пользователь нажимает на значок заметки. Заворачиваю изменение состояния в withAnimation, но заметка появляется с плохой анимацией и строки ниже без анимации продавливаются вниз (резко "подпрыгивают"). Как правильно анимировать расширение, включая сдвиг макета строк ниже?
Вот минимальный рабочий пример, воспроизводящий такое поведение (скопируйте в новый проект SwiftUI и запустите):
import SwiftUI
@main
struct ExpansionApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct HistoryItem: Identifiable, Hashable {
let id: UUID
let title: String
let note: String?
}
// MARK: - View
struct ContentView: View {
// Keeps the sample aligned with the real screen behavior for note expansion.
@State private var expandedNoteItems: Set = []
private let items: [HistoryItem] = [
HistoryItem(id: UUID(), title: "Client A - Morning shift", note: "Short note for entry 1."),
HistoryItem(id: UUID(), title: "Client B - Field visit", note: "Longer note for entry 2 so the row expands more than the others."),
HistoryItem(id: UUID(), title: "Client C - Training", note: nil),
HistoryItem(id: UUID(), title: "Client D - Support", note: "Another note for entry 4."),
HistoryItem(id: UUID(), title: "Client E - Wrap up", note: "Final note for entry 5.")
]
var body: some View {
NavigationStack {
List {
ForEach(items, id: \.id) { item in
VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 12) {
Text(item.title)
.font(.headline)
Spacer()
if item.note != nil {
Button {
toggleNote(for: item.id)
} label: {
Image(systemName: "note.text")
.imageScale(.medium)
}
.buttonStyle(.plain)
}
}
if let note = item.note, expandedNoteItems.contains(item.id) {
Text(note)
.font(.subheadline)
.foregroundStyle(.secondary)
.padding(10)
.background(Color(.secondarySystemBackground))
.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
}
}
.padding(.vertical, 8)
}
}
.listStyle(.plain)
.navigationTitle("History")
}
}
private func toggleNote(for id: UUID) {
withAnimation {
if expandedNoteItems.contains(id) {
expandedNoteItems.remove(id)
} else {
expandedNoteItems.insert(id)
}
}
}
}
// MARK: - Preview
#Preview {
ContentView()
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79876609/swiftui-list-row-expansion-doesn-t-animate-smoothly-items-below-jump-abruptly[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия