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 / 79008142
Accepted
Deepak Sharma
Deepak Sharma
Asked: 2024-09-21 04:12:44 +0800 CST2024-09-21 04:12:44 +0800 CST 2024-09-21 04:12:44 +0800 CST

O SwiftUI mantém o fundo parado enquanto a visualização é arrastada

  • 772

Implementei uma linha do tempo de edição de vídeo de exemplo usando SwiftUI e estou enfrentando problemas. Então, estou dividindo o problema em partes e postando cada problema como uma pergunta separada. No código abaixo, tenho uma linha do tempo simples usando um HStackespaçador esquerdo, espaçador direito (representado como cor preta simples) e uma IU de aparador no meio. O aparador é redimensionado conforme as alças esquerda e direita são arrastadas. Os espaçadores esquerdo e direito também se ajustam em largura conforme as alças do aparador são arrastadas.

Problema : Quero manter as miniaturas de fundo (implementadas atualmente como retângulos simples preenchidos em cores diferentes) no aparador estacionárias enquanto o aparador é redimensionado. Atualmente, elas se movem conforme o aparador é redimensionado, como visto no gif abaixo. Como faço para consertar isso?

insira a descrição da imagem aqui

import SwiftUI

struct SampleTimeline: View {
    
    let viewWidth:CGFloat = 340 //Width of HStack container for Timeline
   
    @State var frameWidth:CGFloat = 280 //Width of trimmer
    
    var minWidth: CGFloat {
        2*chevronWidth + 10
    } //min Width of trimmer
    
    @State private var leftViewWidth:CGFloat = 20
    @State private var rightViewWidth:CGFloat = 20
    
    var chevronWidth:CGFloat {
        return 24
    }
    
    var body: some View {
        
        HStack(spacing:0) {
            Color.black
                .frame(width: leftViewWidth)
                .frame(height: 70)
            
            HStack(spacing: 0) {
            
                Image(systemName: "chevron.compact.left")
                    .frame(width: chevronWidth, height: 70)
                    .background(Color.blue)
                    .gesture(
                        DragGesture(minimumDistance: 0)
                            .onChanged({ value in
                                leftViewWidth = max(leftViewWidth + value.translation.width, 0)
                                
                                if leftViewWidth > viewWidth - minWidth - rightViewWidth {
                                    leftViewWidth = viewWidth - minWidth - rightViewWidth
                                }
                                   
                                frameWidth = max(viewWidth - leftViewWidth - rightViewWidth, minWidth)
                                
                            })
                            .onEnded { value in
                               
                            }
                    )
        
                Spacer()
                
                Image(systemName: "chevron.compact.right")
                    .frame(width: chevronWidth, height: 70)
                    .background(Color.blue)
                    .gesture(
                        DragGesture(minimumDistance: 0)
                            .onChanged({ value in
                                rightViewWidth = max(rightViewWidth - value.translation.width, 0)
                                
                                if rightViewWidth > viewWidth - minWidth - leftViewWidth {
                                    rightViewWidth = viewWidth - minWidth - leftViewWidth
                                }
                                
                                frameWidth = max(viewWidth - leftViewWidth - rightViewWidth, minWidth)
                            })
                            .onEnded { value in
                              
                            }
                    )
                 
            }
            .foregroundColor(.black)
            .font(.title3.weight(.semibold))
          
            .background {
                
                HStack(spacing:0) {
                    Rectangle().fill(Color.red)
                        .frame(width: 70, height: 60)
                    Rectangle().fill(Color.cyan)
                        .frame(width: 70, height: 60)
                    Rectangle().fill(Color.orange)
                        .frame(width: 70, height: 60)
                    Rectangle().fill(Color.brown)
                        .frame(width: 70, height: 60)
                    Rectangle().fill(Color.purple)
                        .frame(width: 70, height: 60)
                }
                
            }
            .frame(width: frameWidth)
            .clipped()
            
            Color.black
                .frame(width: rightViewWidth)
                .frame(height: 70)
        }
        .frame(width: viewWidth, alignment: .leading)
    }
}

#Preview {
    SampleTimeline()
}

Atualização : consegui resolver o problema da seguinte forma, mas ainda sinto que é meio que uma solução alternativa (pois configurei um deslocamento para a visualização de miniaturas). Por favor, poste uma solução melhor e mais precisa se você acha que há alguma (como usar uma máscara que também reduz a largura do quadro do aparador ao mesmo tempo).


import SwiftUI

struct SampleTimeline: View {
    
    let viewWidth:CGFloat = 340 //Width of HStack container for Timeline
   
    @State var frameWidth:CGFloat = 280 //Width of trimmer
    
    var minWidth: CGFloat {
        2*chevronWidth + 10
    } //min Width of trimmer
    
    @State private var leftViewWidth:CGFloat = 20
    @State private var rightViewWidth:CGFloat = 20
    @GestureState private var leftEndPanned = false
    @GestureState private var rightEndPanned = false
    
    var chevronWidth:CGFloat {
        return 24
    }
    
    var body: some View {
        
        HStack(spacing:0) {
            Color.clear
                .frame(width: leftViewWidth)
                .frame(height: 70)
            
            HStack(spacing: 0) {
            
                Image(systemName: "chevron.compact.left")
                    .frame(width: chevronWidth, height: 70)
                    .background(Color.blue)
                    .gesture(
                        DragGesture(minimumDistance: 0)
                            .updating($leftEndPanned, body: { _, state, _ in
                                state = true
                            })
                            .onChanged({ value in
                                leftViewWidth = max(leftViewWidth + value.translation.width, 0)
                                
                                if leftViewWidth > viewWidth - minWidth - rightViewWidth {
                                    leftViewWidth = viewWidth - minWidth - rightViewWidth
                                }
                                   
                                frameWidth = max(viewWidth - leftViewWidth - rightViewWidth, minWidth)
                                
                            })
                            .onEnded { value in
                               
                            }
                    )
        
                Spacer()
                
                Image(systemName: "chevron.compact.right")
                    .frame(width: chevronWidth, height: 70)
                    .background(Color.blue)
                    .gesture(
                        DragGesture(minimumDistance: 0)
                            .updating($rightEndPanned, body: { _, state, _ in
                                state = true
                            })
                            .onChanged({ value in
                                rightViewWidth = max(rightViewWidth - value.translation.width, 0)
                                
                                if rightViewWidth > viewWidth - minWidth - leftViewWidth {
                                    rightViewWidth = viewWidth - minWidth - leftViewWidth
                                }
                                
                                frameWidth = max(viewWidth - leftViewWidth - rightViewWidth, minWidth)
                            })
                            .onEnded { value in
                              
                            }
                    )
                 
            }
            .foregroundColor(.black)
            .font(.title3.weight(.semibold))
            .background {
                
                HStack(spacing:0) {
                    Rectangle().fill(Color.red)
                        .frame(width: 70, height: 60)
                    Rectangle().fill(Color.cyan)
                        .frame(width: 70, height: 60)
                    Rectangle().fill(Color.orange)
                        .frame(width: 70, height: 60)
                    Rectangle().fill(Color.brown)
                        .frame(width: 70, height: 60)
                    Rectangle().fill(Color.purple)
                        .frame(width: 70, height: 60)
                }
                .frame(width: viewWidth - leftViewWidth - rightViewWidth, alignment: .leading)
                .offset(x: -leftViewWidth)
                .background(Color.yellow)
                .clipped()
                
            }
            
            
            Color.clear
                .frame(width: rightViewWidth)
                .frame(height: 70)
        }
        .frame(width: viewWidth, alignment: .leading)
    }
}

#Preview {
    SampleTimeline()
}

  • 1 1 respostas
  • 62 Views

1 respostas

  • Voted
  1. Best Answer
    Benzy Neez
    2024-09-21T16:31:18+08:002024-09-21T16:31:18+08:00

    Atualmente, as cores são mostradas no fundo do aninhado HStack. No entanto, isso HStackestá se movendo, dependendo do tamanho de leftViewWidth. Então, embora você esteja definindo um tamanho de quadro menor no fundo, você não está compensando a posição da pilha.

    Eu sugeriria usar uma abordagem diferente. Em vez de tentar recortar o fundo, deixe-o inalterado e aplique um .maskpara controlar qual parte dele deve ficar visível.

    • Diferentemente de um formato de clipe, uma máscara pode ser acolchoada. Então você pode aplicar o mesmo ajuste à máscara que está sendo usado para os aparadores.
    • Dessa forma, não há necessidade de calcular a largura visível. No entanto, se você precisar saber a largura visível para seus propósitos de edição de vídeo, você pode usar uma propriedade computada para entregá-la. O exemplo atualizado abaixo inclui essa propriedade computada, mas comentada.

    Você aceitou anteriormente outra resposta para arrastar os aparadores que usavam GestureStatevariáveis ​​para rastrear a posição de arrasto (era minha resposta). O exemplo na pergunta está fazendo isso de uma maneira diferente. A versão abaixo é baseada na mesma solução que eu forneci antes. Eu sugeriria que esta é uma maneira mais simples de fazer isso.

    struct SampleTimeline: View {
        let viewWidth: CGFloat = 340 //Width of HStack container for Timeline
        let chevronWidth: CGFloat = 24
        let minWidth: CGFloat = 10
    
        @State private var leftOffset: CGFloat = 0
        @State private var rightOffset: CGFloat = 0
        @GestureState private var leftDragOffset: CGFloat = 0
        @GestureState private var rightDragOffset: CGFloat = 0
    
        private func leftAdjustment(dragOffset: CGFloat) -> CGFloat {
            let maxAdjustment = viewWidth - rightOffset - (2 * chevronWidth) - minWidth
            return max(0, min(leftOffset + dragOffset, maxAdjustment))
        }
    
        private func rightAdjustment(dragOffset: CGFloat) -> CGFloat {
            let maxAdjustment = viewWidth - leftOffset - (2 * chevronWidth) - minWidth
            return max(0, min(rightOffset - dragOffset, maxAdjustment))
        }
    
    //    private var frameWidth: CGFloat {
    //        viewWidth
    //        - (2 * chevronWidth)
    //        - leftAdjustment(dragOffset: leftDragOffset)
    //        - rightAdjustment(dragOffset: rightDragOffset)
    //    }
    
        var body: some View {
            HStack(spacing: 0) {
    
                Image(systemName: "chevron.compact.left")
                    .frame(width: chevronWidth, height: 70)
                    .background(Color.blue)
                    .offset(x: leftAdjustment(dragOffset: leftDragOffset))
                    .gesture(
                        DragGesture(minimumDistance: 0)
                            .updating($leftDragOffset) { value, state, trans in
                                state = value.translation.width
                            }
                            .onEnded { value in
                                leftOffset = leftAdjustment(dragOffset: value.translation.width)
                            }
                    )
    
                Spacer()
    
                Image(systemName: "chevron.compact.right")
                    .frame(width: chevronWidth, height: 70)
                    .background(Color.blue)
                    .offset(x: -rightAdjustment(dragOffset: rightDragOffset))
                    .gesture(
                        DragGesture(minimumDistance: 0)
                            .updating($rightDragOffset) { value, state, trans in
                                state = value.translation.width
                            }
                            .onEnded { value in
                                rightOffset = rightAdjustment(dragOffset: value.translation.width)
                            }
                    )
    
            }
            .foregroundColor(.black)
            .font(.title3.weight(.semibold))
            .background {
                HStack(spacing: 0) {
                    Color.red
                    Color.cyan
                    Color.orange
                    Color.brown
                    Color.purple
                }
                .padding(.vertical, 5)
                .padding(.horizontal, chevronWidth)
                .background(.background)
                .mask {
                    Rectangle()
                        .padding(.leading, leftAdjustment(dragOffset: leftDragOffset))
                        .padding(.trailing, rightAdjustment(dragOffset: rightDragOffset))
                }
            }
            .frame(width: viewWidth)
            .background(.black)
        }
    }
    

    Animação

    • 1

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

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

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 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

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 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
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +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
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +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