SwiftUI 애니메이션 효과를 적용하는 방법에서 각 문자는 textfield?

0

질문

으로 사용자가 문자를 textfield,나는 일부를 표시 애니메이션에서 각각의 새로 입력된 문자(좀처럼 어떻게 현금 응용 프로그램 애니메이션 번호가 그것을 구현하기 위한 알파벳 문자뿐만 아니라).

enter image description here

그것은 그렇게 할 수 있는 이에 SwiftUI? 나의 직관이있을 수 있습니다리를 UIKit 더 미묘한 액세스 textfield의 하지만 요소가 확실하지 않는 방법을 실제로 구현하는 것.

swift swiftui
2021-11-23 14:54:17
1

최고의 응답

1

을 만들 수 있습"가짜" TextField 위에 나타나는 실제 하나입니다. 다음 표시 문자 ForEach.

하실 수 있습니다. FocusState 아이폰 os 에서 15

@available(iOS 15.0, *)
struct AnimatedInputView: View {
    @FocusState private var isFocused: Int?
    @State var text: String = ""
    //If all the fonts match the cursor is better aligned 
    @State var font: Font = .system(size: 48, weight: .bold, design: .default)
    @State var color: Color = .gray
    var body: some View {
        HStack(alignment: .center, spacing: 0){
            //To maintain size in between the 2 views
            Text(text)
                .font(font)
                .opacity(0)
                .overlay(
                    //This textField will be invisible
                    TextField("", text: $text)
                        .font(font)
                        .foregroundColor(.clear)
                        .focused($isFocused, equals: 1)
                )
                .background(
                    ZStack{
                        HStack(alignment: .center, spacing: 0, content: {
                            //You need an array of unique/identifiable characters
                            let uniqueArray = text.uniqueCharacters()
                            ForEach(uniqueArray, id: \.id, content: { char in
                                CharView(char: char.char, isLast: char == uniqueArray.last, font: font)
                                
                            })
                        })
                    }.opacity(1)
                        .minimumScaleFactor(0.1)
                    
                )
            
                .onAppear(perform: {
                    //Bring focus to the hidden TextField
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
                        isFocused = 1
                    })
                })
        }
        .padding()
        .border(color)
        .font(.title)
        //Bring focus to the hidden textfield
        .onTapGesture {
            isFocused = 1
        }
    }
}
struct CharView: View{
    var char: Character
    var isLast: Bool
    var font: Font
    @State var scale: CGFloat = 0.75
    var body: some View{
        Text(char.description)
            .font(font)
            .minimumScaleFactor(0.1)
            .scaleEffect(scale)
            .onAppear(perform: {
                //Animate only if last character
                if isLast{
                    withAnimation(.linear(duration: 0.5)){
                        scale = 1
                    }
                }else{
                    scale = 1
                }
            })
    }
}
@available(iOS 15.0, *)
struct AnimatedInputView_Previews: PreviewProvider {
    static var previews: some View {
        AnimatedInputView()
    }
}
//Convert String to Unique characers
extension String{
    func uniqueCharacters() -> [UniqueCharacter]{
        let array: [Character] = Array(self)
        return array.uniqueCharacters()
    }
    func numberOnly() -> String {
        self.trimmingCharacters(in: CharacterSet(charactersIn: "-0123456789.").inverted)
    }
    
}
extension Array where Element == Character {
    
    func uniqueCharacters() -> [UniqueCharacter]{
        var array: [UniqueCharacter] = []
        
        for char in self{
            array.append(UniqueCharacter(char: char))
        }
        return array
    }
    
}

//String/Characters can be repeating so yu have to make them a unique value
struct UniqueCharacter: Identifiable, Equatable{
    var char: Character
    var id: UUID = UUID()
}

샘플 버전니다. 단과 같은 번호 계산기 샘플

import SwiftUI

@available(iOS 15.0, *)
struct AnimatedInputView: View {
    @FocusState private var isFocused: Int?
    @State var text: String = ""
    //If all the fonts match the cursor is better aligned 
    @State var font: Font = .system(size: 48, weight: .bold, design: .default)
    @State var color: Color = .gray
    var body: some View {
        HStack(alignment: .center, spacing: 0){
            Text("$").font(font)
            //To maintain size in between the 2 views
            Text(text)
                .font(font)
                .opacity(0)
                .overlay(
                    //This textField will be invisible
                    TextField("", text: $text)
                        .font(font)
                        .foregroundColor(.clear)
                        .focused($isFocused, equals: 1)
                        .onChange(of: text, perform: { value in
                               if Double(text) == nil{
                                   //Leaves the negative and decimal period
                                   text = text.numberOnly()
                               }
                               //This condition can be improved.
                               //Checks for 2 occurences of the decimal period
                               //Possible solution
                               while text.components(separatedBy: ".").count > 2{
                                   color = .red
                                   text.removeLast()
                               }

                               //This condition can be improved.
                               //Checks for 2 occurences of the negative
                               //Possible solution
                               while text.components(separatedBy: "-").count > 2{
                                   color = .red
                                   text.removeLast()
                               }
                               color = .gray

                           })
                )
                .background(
                    ZStack{
                        HStack(alignment: .center, spacing: 0, content: {
                            //You need an array of unique/identifiable characters
                            let uniqueArray = text.uniqueCharacters()
                            ForEach(uniqueArray, id: \.id, content: { char in
                                CharView(char: char.char, isLast: char == uniqueArray.last, font: font)
                                
                            })
                        })
                    }.opacity(1)
                        .minimumScaleFactor(0.1)
                    
                )
            
                .onAppear(perform: {
                    //Bring focus to the hidden TextField
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
                        isFocused = 1
                    })
                })
        }
        .padding()
        .border(color)
        .font(.title)
        //Bring focus to the hidden textfield
        .onTapGesture {
            isFocused = 1
        }
    }
}
2021-11-24 02:45:46

감사합니다. 당신이 생각하는 사용이 편집,우리는 어떻게든 프로그래밍 방식으로 변경 Z-index textfield 와 오버레이 텍스트가 있습니까? 아마도 사용 ZStack 보다는 오히려 오버레이입니다. 과를 클릭할 때,텍스트에 우리는 우리를 가져올 수 Textfield 앞으로 편집하고,업데이트 char 배열에 따 편집...그것은 복잡하지만 당신을 감사 솔루션!
PipEvangelist

가능한 한 그러나 매우 복잡성하는 경향이 많습니다.
lorem ipsum

@PipEvangelist 실제로,나는 또 다른 방법을 알아 냈어 그것을 할 수 있습니다. 그것은 보이는 작은 조금 떨어져 있지만 잘 버전입니다. 그것은 편집합니다. 커서 조금 떨어져
lorem ipsum

감사합니다! 이
PipEvangelist

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................