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 / user-22807756

john smith's questions

Martin Hope
john smith
Asked: 2025-03-28 22:12:38 +0800 CST

Como fazer 4 visualizações no HStack alinharem a 1ª à esquerda, a 2ª a ⅓ de distância horizontal, a 3ª a ⅔ de distância horizontal e a 4ª à direita

  • 5

Há uma pergunta semelhante aqui no stackoverflow sobre como fazer isso quando todos são do mesmo tamanho, mas não quando são de tamanhos diferentes. Tenho 4 visualizações em um HStack que quero espaçar uniformemente, mas como o Picker é maior do que os outros 3, é impossível fazer isso usando o Spacer e, como agora são 4 em vez de 3, também não posso mais usar o alinhamento. insira a descrição da imagem aquiQual é a solução para garantir que todos sejam espaçados uniformemente?

import SwiftUI



    
    
    @EnvironmentObject var captureDelegate: CaptureDelegate
    let images = ["person.slash.fill", "person.fill", "person.2.fill", "person.2.fill", "person.2.fill"]
    @Binding var timerPress: Bool
    
    private var rotationAngle: Angle {
            switch captureDelegate.orientationLast {
            case .landscapeRight:
                return .degrees(90)
            case .landscapeLeft:
                return .degrees(-90)  // Fixes the upside-down issue
            default:
                return .degrees(0)
            }
        }
    
    var body: some View {
        HStack() {
            
            Image(systemName: "gearshape")
                .resizable()
                .frame(width: 25, height: 25)
                .foregroundStyle(captureDelegate.cameraPressed ? Color(white: 0.4) : .white  )
                .disabled(captureDelegate.cameraPressed)
                .rotationEffect(rotationAngle)
                .frame(maxWidth: .infinity, alignment: .leading)
                .onTapGesture {
                    if !captureDelegate.cameraPressed {
                        
                    }
                    
                }
            
            Image(systemName: "timer")
                .resizable()
                .frame(width: 25, height: 25)
                .foregroundStyle(captureDelegate.cameraPressed ? Color(white: 0.4) : .white  )
                .disabled(captureDelegate.cameraPressed)
                .rotationEffect(rotationAngle)
                .frame(maxWidth: .infinity)
                .onTapGesture {
                    if !captureDelegate.cameraPressed {
                        timerPress.toggle()
                    }
                    
                }
            

            
            Image(systemName: "timer")
                .resizable()
                .frame(width: 25, height: 25)
                .foregroundStyle(captureDelegate.cameraPressed ? Color(white: 0.4) : .white  )
                .disabled(captureDelegate.cameraPressed)
                .rotationEffect(rotationAngle)
                .frame(maxWidth: .infinity)
                .onTapGesture {
                    if !captureDelegate.cameraPressed {
                        timerPress.toggle()
                    }
                    
                }
            
              


            Picker("Pick a number of people", selection: $captureDelegate.userSelectedNumber) {
                    ForEach(0...4, id: \.self) { i in
                        HStack(spacing: 70) {
                            Image(systemName: self.images[i])
                                .resizable()
                                .frame(width: 20, height: 20)
                                .rotationEffect(rotationAngle)
 
                            Text("\(i)")
                                .font(.system(size: 42))
                                .rotationEffect(rotationAngle)
                            
                        }.tag(i)
                            .rotationEffect(rotationAngle)
                        
                    }
                    
                }
                .tint(.white)
                .clipped()
                .foregroundStyle(captureDelegate.cameraPressed ? Color(white: 0.4) : .white  )
                .disabled(captureDelegate.cameraPressed)
                .rotationEffect(rotationAngle)
                .animation(.easeInOut(duration: 0.5), value: rotationAngle)
                .frame(maxWidth: .infinity, alignment: .trailing)

        }
        .font(.system(size: 24))
        .padding([.leading,.trailing], 15)
    }
}

Tentei usar o espaçador, mas não funciona porque eles não são todos do mesmo tamanho. Quando eu tinha 3 visualizações, obtive sucesso usando o alinhamento à esquerda no centro e à direita, mas agora que há 4 visualizações, não funciona mais.

Aqui tentei usar um ZStack para posicioná-los, colocando as duas vistas centrais no mesmo HStack:

 ZStack {
            
            HStack {
                Image(systemName: "gearshape")
                    .resizable()
                    .frame(width: 25, height: 25)
                    .foregroundStyle(captureDelegate.cameraPressed ? Color(white: 0.4) : .white  )
                    .disabled(captureDelegate.cameraPressed)
                    .rotationEffect(rotationAngle)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .onTapGesture {
                        if !captureDelegate.cameraPressed {
                            
                        }
                        
                    }
                
                
                
                Picker("Pick a number of people", selection: $captureDelegate.userSelectedNumber) {
                    ForEach(0...4, id: \.self) { i in
                        HStack(spacing: 70) {
                            Image(systemName: self.images[i])
                                .resizable()
                                .frame(width: 20, height: 20)
                                .rotationEffect(rotationAngle)
                            
                            Text("\(i)")
                                .font(.system(size: 42))
                                .rotationEffect(rotationAngle)
                            
                        }.tag(i)
                            .rotationEffect(rotationAngle)
                        
                    }
                    
                }
                .tint(.white)
                .clipped()
                .foregroundStyle(captureDelegate.cameraPressed ? Color(white: 0.4) : .white  )
                .disabled(captureDelegate.cameraPressed)
                .rotationEffect(rotationAngle)
                .animation(.easeInOut(duration: 0.5), value: rotationAngle)
                .frame(maxWidth: .infinity, alignment: .trailing)
            }
            
            HStack {
               
                Text("\(captureDelegate.totalPhotosToTake)")
                    .font(.system(size: 15))
                    .foregroundStyle(.white)
                    .fontWeight(.bold)
                    .padding(.horizontal, 9)
                    .padding(.vertical, 5)
                    .overlay(
                        RoundedRectangle(cornerRadius: 5).stroke(.white, lineWidth: 2)
                    )
                    .frame(maxWidth: .infinity, alignment: .center)
                
                Image(systemName: "timer")
                    .resizable()
                    .frame(width: 25, height: 25)
                    .foregroundStyle(captureDelegate.cameraPressed ? Color(white: 0.4) : .white  )
                    .disabled(captureDelegate.cameraPressed)
                    .rotationEffect(rotationAngle)
                    .onTapGesture {
                        if !captureDelegate.cameraPressed {
                            timerPress.toggle()
                        }
                        
                    }
                    .frame(maxWidth: .infinity, alignment: .center)

              
            }
        
        }
        .font(.system(size: 24))
        .padding([.leading,.trailing], 15)

insira a descrição da imagem aqui

E mudar os alinhamentos das duas vistas centrais de central para teste e entrelinha produz este efeito:

insira a descrição da imagem aqui

  • 2 respostas
  • 50 Views
Martin Hope
john smith
Asked: 2025-03-24 20:13:53 +0800 CST

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

  • 6

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 respostas
  • 34 Views
Martin Hope
john smith
Asked: 2024-08-08 01:31:27 +0800 CST

Como adicionar algum espaçamento nas marcas esquerda e direita ou do eixo X no LineMark

  • 5

Eu tenho um LineMark onde minhas marcas do eixo X estão muito próximas das bordas e um pouco difíceis de ler:

Chart {
  ForEach(numberWorkouts) { numberworkouts in
    if dateState == .weeks {
      LineMark(
        x: .value("Date", numberworkouts.date, unit: .day),
        y: .value("Total", numberworkouts.numberOfWorkouts)
      )
      .interpolationMethod(.catmullRom)
      .symbol {
        Circle()
          .fill(.blue)
          .frame(width: 7, height: 7)
      }
    } else {
      LineMark(
        x: .value("Date", numberworkouts.date, unit: .month),
        y: .value("Total", numberworkouts.numberOfWorkouts)
      )
      .symbol {
        Circle()
          .fill(.blue)
          .frame(width: 7, height: 7)
      }
    }
  }
}
.chartYAxis {
  AxisMarks(position: .leading)
}
.chartYAxisLabel(position: .leading, alignment: .center) {
}
.chartYAxis {
  AxisMarks(stroke: StrokeStyle(lineWidth: 0))
}
.chartXAxis {
  if dateState == .weeks {
    AxisMarks(preset: .aligned, values: .stride(by: .day, count: 7)) {
      AxisValueLabel(format: .dateTime.month(.twoDigits).day())
    }
  } else {
    AxisMarks(values: .stride(by: .month)) {
      AxisValueLabel(format: .dateTime.month(.abbreviated), centered: true)
    }
  }
}
//.chartForegroundStyleScale(dataType == .MaxWeight ? ["Max Weight": Color.blue] : ["One Rep Max": Color.blue] )
.chartForegroundStyleScale(["No. of Workouts": Color.blue])
.chartLegend(.visible)
.aspectRatio(1.7, contentMode: .fit)
//.padding()

17/7 muito perto

como faço para empurrar 17/7 e 07/08 um pouco para dentro, tentei aplicar preenchimento ao gráfico, mas isso aplica preenchimento à parte externa do LineMark e o LineMark não aceita preenchimento como modificador

swift
  • 1 respostas
  • 25 Views
Martin Hope
john smith
Asked: 2024-08-07 18:57:04 +0800 CST

Como limpar um TextField quando ele está vinculado a um objeto SwiftData que não é opcional

  • 4

Digamos que você tenha um objeto SwiftData que não permite opcionais:

@Model
class MySet: Identifiable {
    var id: UUID
    var weight: Int
    var reps: Int
    var isCompleted: Bool
    var exercise: Exercise

Então você obtém dos dados do MySet uma lista desses MySets e os anexa a um estado:

  @State var sets: [MySet]

            if let newSets = exercise.sets {    //unwrapping the passed exercises sets
                if (!newSets.isEmpty) {     //we passed actual sets in so set them to our set
                    sets = newSets
                }

E você usa essa lista de estados em um ForEach e vincula o Textfield diretamente aos dados assim:

 ForEach($sets){ $set  in

 TextField("\(set.weight)", value: $set.weight, formatter: NumberFormatter())
                                        .keyboardType(.decimalPad)

   TextField("\(set.reps)", value: $set.reps,formatter: NumberFormatter())
                                        .keyboardType(.decimalPad)
                                    


}

Isso vinculará tudo o que estiver escrito no TextField diretamente ao objeto SwiftData, o que é um problema porque, digamos que você tenha 50 escritos e queira alterá-lo para 60, você precisa limpar o 50 para escrever o 60 e já que o objeto SwiftData não permite nulo, permitirá que você remova o 0, mas não o 5. Existe alguma maneira de remediar isso sem que o objeto swiftData permita opcionais, por exemplo, capturar a limpeza do TextField e torná-lo 0 em vez de nulo quando for limpo?

Tento consertar isso vinculando TextField a um novo estado e usando onChanged:

@State private var reps: Int = 0
@State private var weight: Int = 0

                            TextField("\(myset.weight)", value: $weight, formatter: NumberFormatter())
                                .keyboardType(.decimalPad)
                             
                                .onChange(of: weight) { newWeight in
                                    // Code to run when propertyToWatch changes to newValue
                                    if newWeight != 0 {
                                        myset.weight = newWeight
                                    }
                                }

mas agora ele está mudando cada repetição e peso de todas as séries quando eu digito uma em vez de apenas aquela em que estou digitando

swift
  • 2 respostas
  • 50 Views

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