We can change the image with the help of a button using state variable as Boolean. But how do we achieve that using a string variable?
For Example:
If State variable is a bool:-
Image(systemName: self.typeClicked ? "heart.fill" : "heart.fill")
what will come in the place of " self.typeClicked ? "heart.fill" : "heart.fill" " if the state variable is String?
When the typeClicked = "success" the image should change, if it is other than "success" the image should retain its previous condition.
What I have tried so far:
State variables:
@State private var type: String = "success"
@State private var typeClicked: Bool = false
@StateObject var viewModel = addWishlist()
MyView :
VStack{
HStack {
Image("resort1")
Spacer()
Button {
if viewModel.responses?.type == "success" {
typeClicked.toggle()
} else {
typeClicked = false
}
} label: {
Image(systemName: self.typeClicked ? "heart.fill" : "heart.fill")
.font(.system(size: 25))
.foregroundColor(self.typeClicked ? .red : Color.init(uiColor: .systemGray3))
}
}
.padding()
}
Network class:
class addWishlist: ObservableObject {
@Published private(set) var records: addRecord?
@Published private(set) var responses: add?
func loadData() {
let url = URL(string: addwishlist_URL)
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
let postString = "roomid=xxxxxxxxxxx&emailid=xxxxxxxxxxxx"
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
do {
if let todoData = data {
let decodedData = try JSONDecoder().decode(add.self, from: todoData)
DispatchQueue.main.async {
self.records = decodedData.record
print(decodedData.record)
print(decodedData.type)
}
} else {
print("No data")
}
} catch {
print(error)
}
}
task.resume()
}
}
structs:
struct add: Codable { var type: String let record: addRecord }
I want my view to be changed only with "type". which is "type": "success" in my api response.
responsesoptional?