SwiftUI: Text animation not working from the second line - swiftui

I am trying to make sure I have a consistent animation throughout this dynamic Text view as I'm typing in the TextField.
import SwiftUI
struct ContentView: View {
#ObservedObject var viewModel = ContentViewModel()
var body: some View {
VStack {
HStack {
Text("Write this word: ")
Text(String(viewModel.textValue))
}
TextField("Write here:", text: $viewModel.enteredTextValue)
.padding(10)
.border(Color.green, width: 1)
Text(viewModel.enteredTextValue)
.animation(.easeIn(duration: 0.5)) // added animation here.
Toggle(isOn: $viewModel.textsMatch) {
Text("Matching?")
}
.disabled(true)
.padding()
}.padding()
}
}
class ContentViewModel: ObservableObject {
#Published var textValue: String = "Hello"
#Published var enteredTextValue: String = "" {
didSet {
textsMatch = (enteredTextValue == textValue)
}
}
#Published var textsMatch: Bool = false
}
Notice the animation is smooth in the fist line and then drops at second line?
Would appreciate any help on this please.
FYI code taken from here (Combine framework).
Many thanks!

Related

The searchable modifier on tvOS, when inside a NavigationView, doesn't allow refocusing the search bar

When using a NavigationView and a ScrollView with searchable, as soon as you focus a item in the LazyVGrid the search bar collapses the keyboard, and it's no longer possible to re-focus the search bar to change the query.
It doesn't matter if the .searchable modifier is applied to the ScrollView or the NavigationView.
The more I look at it, the more it appears to be a SwiftUI bug on tvOS, but I would still like to find a workaround, if possible.
Sample code which reproduces the problem:
import SwiftUI
struct ContentView: View {
private var fruits = ["Apples", "Pears", "Oranges", "Plums", "Pineapples", "Bananas"]
#State private var items: [String]
#State private var searchText: String = ""
init() {
self.items = fruits
}
var body: some View {
NavigationView {
ScrollView {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 300))], spacing: 40) {
ForEach(items, id: \.self) { item in
NavigationLink(destination: DetailView(text: item)) {
Text(item)
}
}
}
}
.searchable(text: $searchText)
.onChange(of: searchText) { query in
if query.isEmpty {
items = fruits
} else {
items = fruits.filter { $0.contains(query) }
}
}
}
}
}
struct DetailView: View {
let text: String
var body: some View {
Text(text)
}
}
Gif illustrating the problem:

TextField #State property value = ""

I'm studying SwiftUI and I'm having a hard time dealing with TextField.
When I do onCommit, I tried to put "" in the #State Property value, but there was no response.
What I'm trying to do is click the'retrun' key in TextField and I want to show you the gap where the text created disappeared.
struct TodoTextFieldView: View {
#EnvironmentObject var listViewModel: ListViewModel
#State var textFieldText = ""
var title: String = "here typing line"
var body: some View {
VStack{
HStack(spacing: 5){
Text("🔥")
.font(.title)
TextField("\(title)",
text: $textFieldText,
onCommit:{ addItem()
//
})
.disableAutocorrection(true)
.underline()
.font(.headline)
}.padding(.leading, 40)
}.padding(16)
}
func addItem() {
listViewModel.addItem(title: textFieldText)
textFieldText = "" // This is where I want to do it.
print(textFieldText)
}
This is a parent view.
struct ContentView: View {
#EnvironmentObject var listViewModel: ListViewModel
var body: some View {
VStack {
TodayView()
Spacer()
TodoTextFieldView()
Spacer()
/// List view
List{
ForEach(listViewModel.items) { item in
ListView(item: item)
.onTapGesture {
withAnimation(.linear){
listViewModel.updateItem(item: item)
}
}
}
.onDelete(perform: listViewModel.deleteItem) // Delete
.onMove(perform: listViewModel.moveItem) // Edit
}.listStyle(PlainListStyle())
}.navigationBarItems(trailing: EditButton()) // Edit Button
.padding()
}
}
#State var textFieldText = ""
The value was directly added to the state property. But there is no reaction.
textFieldText = ""
Emptying the binding property of TextField inside the Task block works for me.
func addItem() {
listViewModel.addItem(title: textFieldText)
Task {
textFieldText = ""
}
}

SwiftUI TextFields based on #Published array not updating

I am trying to lay out a bunch of CustomTextViews which can toggle between a SwiftUI TextField or Text view.
Consider this example.
import SwiftUI
struct ContentView: View {
#StateObject var doc: Document = Document()
var body: some View {
ForEach(doc.lines, id: \.self) { line in
HStack {
ForEach(line, id: \.self) { word in
CustomTextView(text: word, document: doc)
.fixedSize()
}
Spacer()
}
}
.frame(width: 300, height: 300)
.background(.cyan)
}
}
struct CustomTextView: View {
#State var text: String
#State var isEditing: Bool = false
#ObservedObject var document: Document
var body: some View {
if isEditing {
TextField("", text: $text)
.onSubmit {
isEditing.toggle()
// NOTE: reset document anytime a word ends in "?"
if text.last! == "?" {
print("resetting")
document.lines = [["Reset"]]
print(document.lines)
}
}
} else {
Text(text)
.onTapGesture {
isEditing.toggle()
}
}
}
}
class Document: ObservableObject {
#Published var lines: [[String]] = [["Hello"]]
}
What I want to happen is that I should be able to indefinitely reset the text. But instead, the view only resets correctly once (see gif). All further updates to reset document.lines are not correct, even though the print statements show that the #Published property lines is clearly changing.
What am I doing wrong?
You need to update the textfield text with document.lines[index] where index is index of line into document.lines array. So you need to update like below.
struct CustomTextView: View {
#State var isEditing: Bool = false
#ObservedObject var document: Document
var body: some View {
if isEditing {
TextField("", text: $document.lines[index])
.onSubmit {
isEditing.toggle()
// NOTE: reset document anytime a word ends in "?"
if document.lines[index].last! == "?" {
print("resetting")
document.lines = [["Reset"]]
print(document.lines)
}
}
} else {
Text(text)
.onTapGesture {
isEditing.toggle()
}
}
}
}

SwiftUI - Subtotal TextField entries across multiple views

I have multiple views created by a ForEACH. Each View has a textfield where a user can enter a number. I would like to subtotal each entry in each view. In other words subtotal the binding in each view.
Is my approach wrong?
ForEach(someArray.allCases, id: \.id) { item in
CustomeRowView(name: item.rawValue)
}
struct CustomeRowView: View {
var name: String
#State private var amount: String = ""
var body: some View {
VStack {
HStack {
Label(name, systemImage: image)
VStack {
TextField("Amount", text: $amount)
.frame(width: UIScreen.main.bounds.width / 7)
}
}
}
}
}
Any help would be greatly appreciated.
there are many ways to achieve what you ask. I present here a very
simple approach, using an ObservableObject to keep the info in one place.
It has a function to add to the info dictionary fruits.
A #StateObject is created in ContentView to keep one single source of truth.
It is passed to the CustomeRowView view using #ObservedObject, and used to tally
the input of the TextField when the return key is pressed (.onSubmit).
import SwiftUI
#main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class FruitCake: ObservableObject {
#Published var fruits: [String : Int] = ["apples":0,"oranges":0,"bananas":0]
// adjust for you purpose
func add(to name: String, amount: Int) {
if let k = fruits.keys.first(where: {$0 == name}),
let sum = fruits[k] {
fruits[k] = sum + amount
}
}
}
struct ContentView: View {
#StateObject var fruitCake = FruitCake()
var body: some View {
VStack {
ForEach(Array(fruitCake.fruits.keys), id: \.self) { item in
CustomeRowView(name: item, fruitCake: fruitCake)
}
}
}
}
struct CustomeRowView: View {
let name: String
#ObservedObject var fruitCake: FruitCake
#State private var amount = 0
var body: some View {
HStack {
Label(name, systemImage: "info")
TextField("Amount", value: $amount, format: .number)
.frame(width: UIScreen.main.bounds.width / 7)
.border(.red)
.onSubmit {
fruitCake.add(to: name, amount: amount)
}
// subtotal
Text("\(fruitCake.fruits[name] ?? 0)")
}
}
}

TextField not showing placeholder text when cleared programmatically. is there a way to remove this behavior?

I have the following code. When I clear the TextField binding property on the view model, the placeholder text isn't shown again until the TextField becomes first responder again.
struct SomeView: View {
#ObservedObject var viewModel = ViewModel()
var body: some View {
HStack {
TextField("Enter something here..", text: $viewModel.text)
.textFieldStyle(RoundedBorderTextFieldStyle())
.disableAutocorrection(true)
Spacer()
Button("Reset") { self.viewModel.reset() }
}
.padding()
}
}
class ViewModel: ObservableObject {
#Published var text = ""
func reset() {
text = ""
}
}