Last active
September 10, 2024 05:57
-
-
Save akardas16/8b5fbe5555a6fe43ebdda443e5b5aab2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// TypeWriterView.swift | |
// | |
// Created by Abdullah Kardaş on 10.01.2023. | |
// | |
import SwiftUI | |
struct TypeWriterView: View { | |
@State var text: String = "" | |
@State var isStop = false | |
let finalText: String | |
let font:Font | |
let alignment:Alignment | |
@State var animating = false | |
var body: some View { | |
VStack(alignment: .leading,spacing: 45) { | |
Toggle(isOn: $isStop) { | |
Text("Stop Loop and let text finish") | |
}.padding(.horizontal) | |
TextField("Type...", text: $text).padding(.horizontal).padding(.vertical,12).background(Color.gray.cornerRadius(10)).padding(.horizontal).foregroundColor(.white) | |
}.onAppear { | |
text = "" | |
animating = true | |
typeWriter() | |
}.onDisappear { | |
animating = false | |
text = "" | |
} | |
} | |
func typeWriter(at position: Int = 0) { | |
if animating { | |
if position == 0 { | |
text = "" | |
} | |
if position < finalText.count { | |
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { | |
if finalText[position] == " "{ | |
text.append(" ") | |
text.append(finalText[position + 1]) | |
typeWriter(at: position + 2) | |
}else{ | |
text.append(finalText[position]) | |
typeWriter(at: position + 1) | |
} | |
} | |
}else if position == (finalText.count) { | |
text = "Hello, World!" | |
if isStop.not() { | |
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4){ | |
typeWriter() | |
} | |
} | |
} | |
} | |
} | |
} | |
struct TypeWriterView_Previews: PreviewProvider { | |
static var previews: some View { | |
TypeWriterView(finalText: "Hello, World!", font: .title3, alignment: .leading).foregroundColor(.cyan).frame(width: .infinity,alignment: .leading) | |
} | |
} | |
extension String { | |
subscript(offset: Int) -> Character { | |
self[index(startIndex, offsetBy: offset)] | |
} | |
} | |
extension Bool{ | |
func not() -> Bool{ | |
return !self | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment