AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79531035
Accepted
john smith
john smith
Asked: 2025-03-24 20:13:53 +0800 CST2025-03-24 20:13:53 +0800 CST 2025-03-24 20:13:53 +0800 CST

SwiftUI LazyHStack em ScrollView causa problemas de rolagem no seletor de roda personalizado

  • 772

Eu tenho uma Roda de Rolagem Horizontal Personalizada que conecta um modelo que salva valor em um UserDefault usando didset. Quando eu uso um HStack regular, o valor está correto e salva corretamente em UserDefaults quando você rola para um novo número, mas o problema é que quando a visualização é mostrada inicialmente, ela sempre está em 0 quando eu confirmo que o valor passado não é zero. Quando eu mudo para um LazyHStack, ele funciona como recuado, mas vem com bugs estranhos onde ele não rola para a posição correta e às vezes quebra a rolagem. :

Onde o userDefaults está sendo definido.

   @Published var captureInterval: Int = 1 {
           didSet {
               UserDefaults.standard.set(captureInterval, forKey: "captureInterval")
           }
       }
    @Published var startCaptureInterval: Int = 2 {
           didSet {
               UserDefaults.standard.set(startCaptureInterval, forKey: "startCaptureInterval")
           }
       }
    

A visão em questão:

struct WheelPicker: View {
    
    var count: Int      //(20 passed in)
    var spacing: CGFloat = 80
    @Binding var value: Int
    
    //TODO: Add some Haptic Feedback
    
    var body: some View {
        GeometryReader { geometry in
            let size = geometry.size    //Size of the entire Parent Container
            let horizontalPadding = geometry.size.width / 2
            
            ScrollView(.horizontal, showsIndicators: false) {
               LazyHStack(spacing: spacing) {
                    ForEach(0..<count, id: \.self) { index in
                        Divider()
                            .foregroundStyle(.blue)
                            .frame(width: 0, height: 30, alignment: .center)
                            .frame(maxHeight: 30, alignment: .bottom)
                            .overlay(alignment: .bottom) {
                                Text("\(index)")
                                    .font(.system(size: index == value ? 25 : 20))
                                    //.fontWeight(.semibold)
                                    .textScale(.secondary)
                                    .fixedSize()    //Not letting any parent Resize the text
                                    //.offset(y: 38)   //how much to push off the bottom of the text from bottom of Divider
                                    .offset(y: index == value ? 43 : 38)    //adjusting for the 5 extra points the bigger text has
                            }
                           
                    }
                }
                .scrollTargetLayout()
                .frame(height: size.height)
                
                
            }
            .scrollIndicators(.hidden)
            .scrollTargetBehavior(.viewAligned)                     //will help us know which index is at the center
            .scrollPosition(id: Binding<Int?>(get: {    //needed because scrollPositon wont accept a Binding int
                let position: Int? = value      
                return position
            }, set: { newValue in
                    if let newValue {
                    value = newValue    //simply taking in the new value and pass it back to the binding
                }
            }))
            .overlay(alignment: .center, content: {
                Rectangle()     //will height the active index in wheelpicker by drawing a small rectangle over it
                    .frame(width: 1, height: 45) //you can adjust its height to make it bigger
            })
            .safeAreaPadding(.horizontal, horizontalPadding)        //makes it start and end in the center
            
          
        }
    }
    
    
   
}

#Preview {
    @Previewable @State var count: Int = 30
    @Previewable @State var value: Int = 5
    WheelPicker(count: count, value: $value)
}

O que tentei até agora é criar uma variável Int? que inicializo em .task para ser igual ao valor, passo como scrollPosition e adiciono um OnTap no HStack para definir o valor e a nova variável Int?. Isso faz com que a rolagem e a posição inicial funcionem perfeitamente, mas não define mais os userDefaults.

  • 2 2 respostas
  • 34 Views

2 respostas

  • Voted
  1. Best Answer
    Sweeper
    2025-03-24T20:35:09+08:002025-03-24T20:35:09+08:00

    Parece que o scroll simplesmente não está rolando para a posição inicial de scroll por algum motivo. Você pode rolar manualmente onAppearusando um ScrollViewReader.

    ScrollViewReader { scrollProxy in
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: spacing) {
                // ....
            }
            .scrollTargetLayout()
            .frame(height: size.height)
        }
        .scrollIndicators(.hidden)
        .scrollTargetBehavior(.viewAligned)
        .scrollPosition(id: Binding($value)) // you can just create a Binding<Int?> like this
        .onAppear {
            scrollProxy.scrollTo(value) // manually scroll to the initial position
        }
    }
    .overlay(...)
    
    • 0
  2. Andrei G.
    2025-03-25T11:06:57+08:002025-03-25T11:06:57+08:00

    Se você usar um HStackwith .scrollPosition(id:_), ele não saberá qual está selecionado em appear, já que a vinculação da posição de rolagem é inicialmente nil. Para corrigir isso, você normalmente definiria um valor para a vinculação da posição de rolagem em appear, o que não é possível com a vinculação personalizada como você a usou.

    Para evitar outras dores de cabeça, eu simplesmente criaria um estado local e então o "sincronizaria" com a vinculação original:

    @State private var currentValue: Int?
    

    Use-o para .scrollPosition:

    .scrollPosition(id: $currentValue, anchor: .center)
    

    Em seguida, defina um valor para aparecer e atualize a ligação original sempre que ela mudar:

    .onAppear {
        currentValue = value
    }
    .onChange(of: currentValue) {
        if let newValue = currentValue {
            value = newValue
        }
    }
    

    Quanto ao restante, veja o código completo abaixo sobre como ele poderia ser estruturado para evitar ter que usar largura e altura de quadro definidas e ter mais flexibilidade:

    import SwiftUI
    
    struct WheelPicker: View {
        
        //Parameters
        var count: Int
        var spacing: CGFloat = 80
        @Binding var value: Int
        
        @State private var currentValue: Int?
        
        //Body
        var body: some View {
            
            GeometryReader { geometry in
                let size = geometry.size    //Size of the entire Parent Container
                let horizontalPadding = (size.width - spacing) / 2 // <-  subtract the width of the content
                
                VStack(spacing: 5) {
                    Rectangle()
                        .frame(width: 1)
                    
                    ScrollView(.horizontal, showsIndicators: false) {
                        HStack(spacing: 0) {
                            ForEach(0..<count, id: \.self) { index in
                                
                                Color.clear// <- fixed width container since numbers may vary in size/width
                                    .containerRelativeFrame(.horizontal, alignment: .center)
                                    .overlay {
                                        Text("\(index)")
                                    }
                                    //Use scrollTransition to scale instead of font size
                                    .scrollTransition { content, phase in
                                        content
                                            .scaleEffect(phase.isIdentity ? 1.3 : 1)
                                            .opacity(phase.isIdentity ? 1 : 0.4)
                                    }
                            }
                        }
                        .scrollTargetLayout()
                    }
                    .scrollIndicators(.hidden)
                    .scrollTargetBehavior(.viewAligned)
                    .scrollPosition(id: $currentValue, anchor: .leading)
                    .sensoryFeedback(.alignment, trigger: value) // <- haptic feedback
                    .contentMargins(.horizontal, horizontalPadding) //makes it start and end in the center
                }
                .onAppear {
                    currentValue = value
                }
                .onChange(of: currentValue) {
                    if let newValue = currentValue {
                        value = newValue
                    }
                }
                .frame(height: 100) // <- height of the picker
                .containerRelativeFrame(.vertical) // <- optional, to center everything vertically
            }
        }
    }
    
    #Preview {
        @Previewable @State var count: Int = 30
        @Previewable @State var value: Int = 8
        WheelPicker(count: count, spacing: 80, value: $value)
            .onChange(of: value) {
                print("value is: \(value)") // <- this can be used to update other things, like UserDefaults
            }
    }
    
    • 0

relate perguntas

  • Adicionar número de série para atividade de cópia ao blob

  • A fonte dinâmica do empacotador duplica artefatos

  • Selecione linhas por grupo com 1s consecutivos

  • Lista de chamada de API de gráfico subscritoSkus estados Privilégios insuficientes enquanto os privilégios são concedidos

  • Função para criar DFs separados com base no valor da coluna

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve