I have a ForEach listing a lot of eventos, having 1 image button for each of them.
When the button is clicked, I will open a modal with the selectedEvento.
The problem is even though I've the line "self.selectedEvento = evento" inside of the button actions, when I click the button for the first time, the selectedEvento is being passed as nil.
However if I click a second button, the process will happen succesfully.
Code:
...
@State var showModal = false
@State var selectedEvento: Evento!
...
ForEach(store.eventos) { evento in
VStack() {
Button(action: {
self.selectedEvento = evento
self.showModal.toggle()
}) {
WebImage(url: evento.thumbnail)
}
}
.sheet(isPresented: $showModal) {
if self.selectedEvento != nil {
//open detailView
} else {
Text("Some Error State goes here")
}
}
}
** Why is this happening ?
Shoudn't the first click also to be passing the selectedEvento ? Why it doesnt happen ?
Thx
Post
Replies
Boosts
Views
Activity
In my SwiftUI project, I am trying to convert HTML to Text.
Text("h1Test/h1p Test/pbr/spanTest/spanulliitem1/liliitem2/li/ul")
.font(.body)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom, 16)
Is there a way to make it happen ?
Thank you
In my SwiftUI app, I have a TabBar with 2 items:
a) TabItem1
b) TabItem2
However on the View itself, I created 2 buttons:
a) Button A
b) Button B
Now I need to switch TabBar items, using the buttons on the View. How can I do this ?
*******
Button(action: {
//call tabItem 1
})
{
Text("TabItem1")
}
Button(action: {
//call tabItem 2
})
{
Text("TabItem2")
}
***************************
TabView {
TabView1View()
.tabItem {
Text("TabItem1")
}
TabView2View()
.tabItem {
Text("TabItem2")
}
Thank you
When rendering HTML into my view, I have the following part:
struct HTMLStringView: UIViewRepresentable {
let htmlContent: String
func makeUIView(context: Context) - WKWebView {
return WKWebView()
}
func updateUIView(_ uiView: WKWebView, context: Context) {
let headerString = "headmeta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'/head"
uiView.loadHTMLString(headerString + htmlContent, baseURL: nil)
}
}
Everything works fine but some problems: If the html is long, It will create an another vertical scrollbar inside my view (so I will have 2 scrollbars)
Font family and size still dont match the original view.
How can I fix it ?
Thx
I have a button on my modal and I want to dismiss the modal with animation. Right now it just closes it.
HStack {
Spacer()
Image(systemName: "xmark")
.font(.system(size: 16, weight: .medium))
.foregroundColor(.white)
.frame(width: 36, height: 36)
.background(Color.black)
.clipShape(Circle())
.onTapGesture {
self.showModal.toggle() -- HERE
}
}
How can I do that ?
Thx
When I use:
Text("My text \nhas a break line")
The output is:
My text
has a break line
PERFECT - I have "My text" and in the next line, I have "has a break line"
However if I have:
Text(mymodel.description)
//where this is returning from an API call and mymodel.description contains "My text \nhas a break line")
It doesn't work.
The output is:
My text \nhas a break line
Why ?
I am trying to call an API, but I need to pass the parameter via querystring.
But somehow it's not working. Where is the mistake ?
func getProductById(productId: String, completion: @escaping (Product) -> ()) {
guard let url = URL(string: "https://mysite.com/product/" + productId) else { return }
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(with: request) { (data, request, error) in
guard let data = data else { return }
do {
let product = try! JSONDecoder().decode(Product.self, from: data)
DispatchQueue.main.async {
completion(product)
}
}
catch {
//print(error)
}
}
.resume()
}
I have a view which goes to my Store, gets data from an API and bringing back to the view.
var productId = 123
@ObservedObject var productStore = ProductStore()
init() {
productStore.getById(productId: self.productid)
}
The object from ProductStore is coming back but when I try to use it:
Text(self.productStore.product!.title)
I get: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Why this is happening if the object doesnt have nil values ?
When instanciating an array of ProductModel, I do this way and everything works fine:
@Published var products = [ProductModel]()
However If I just want one instance, I have an error:
@Published var product = ProductModel()
Missing argument for parameter 'from' in call
Why is this problem happening ?
Thx
I have this API call in my application.
For some reason, the response is coming back nil.
If I try the right URL, a JSON will be returned and all the nodes filled out.
So I'm trying to get the error inside the
if let error = error { but even putting a breaking point in there, the code is never reached.
What am I doing wrong ?
Thanks
func getProductById(productId: Int, completion: @escaping (ProductModel) -> ()) {
guard let url = URL(string: "https://mysite/api/products/82") else { return } var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: request) { (data, request, error) in
if let data = data {
print("data") } if let error = error {
print("error") }
guard let data = data else { return } do {
let product = try! JSONDecoder().decode(ProductModel.self, from: data)
DispatchQueue.main.async {
completion(product)
}
} catch {
print(error)
} }
.resume()
When developing my code, I have seen people saying I should create a Store (eg: ProductStore) with ObservableObject/Published and inside of it, create functions to call the API (eg: ProductAPI)
What's the reason for that ?
Thank you
Checking an existing code, I could see an environmentObject set in my main file.
What does it mean ? it means I am creating an instance of my store and making them available for the entire application ? Like a static instance in other languages ? or there is something else ?
Thank you,
@main
struct myApp: App {
var myStore = MyStore()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(myStore)
Trying to understand API calls in SwiftUI, I got some doubt about environmentObject.Here, I have a file Network.swift which contains a method to get Users.
So I create an environmentObject on my ProjectNameApp.swift file (see code).But this is my question:
Let's say I have an another file Products.swift containing methods related to the products API. How I would set it in my ProjectNameApp.swift file ?
// Network.swift
import SwiftUIclass Network: ObservableObject {
@Published var users: [User] = [] func getUsers() {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { fatalError("Missing URL") } let urlRequest = URLRequest(url: url) let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if let error = error {
print("Request error: ", error)
return
} guard let response = response as? HTTPURLResponse else { return } if response.statusCode == 200 {
guard let data = data else { return }
DispatchQueue.main.async {
do {
let decodedUsers = try JSONDecoder().decode([User].self, from: data)
self.users = decodedUsers
} catch let error {
print("Error decoding: ", error)
}
}
}
} dataTask.resume()
}
}
// ProjectNameApp.swift@main
struct ProjectNameApp: App {
var network = Network() var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(network)
}
}
}
Would be the right implementation something like this ? For each API group a new environmentObject ?
// ProjectNameApp.swift@main
struct ProjectNameApp: App {
var network = Network()
var product = Product() var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(network)
.environmentObject(product)
}
}
}
Thank you
I have a JSON from my backend which returns:
[
{
productId : 1
name: productA
},
{
productid: 2
name: productB
}
}
And on my SwiftUI project I have a model:
struct ProductModel: Identifiable, Codable, Hashable {
//var id = UUID()
var productId = Int
var name = String
}
In my View, when I do a foreach to present all the products coming from my JSON, I got a message saying my model needs to be Identifiable to be using the foreach.
That was the reason I created the var id = UUID() on my model.
Now I dont have the foreach error message, however, I get the error:
Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "id", intValue: nil)
Shouldn't it be ok since I am creating the ID on my model ?
Thank you !
I have an ObservableObject class that can return 2 different @published vars (product or products), depending on the function I call.
But when I define the published vars, I am having an error message "Missing argument for parameter 'from' in call".
It just happens for the first published var.
What's the mistake?
Thx
class ProductStore: ObservableObject {
@Published var product = ProductModel() //getting error here
@Published var products: [ProductModel] = []
func getProducts() {
ProductApi().getProducts() { (products) in
self.products.append(contentsOf: products)
}
}
func getProductById(productId: Int) {
ProductApi().getProductById(productId: productId) { (product) in
self.product = product
} }
}