Random Image when pressing a button in SwiftUI [closed] - swift

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to make a random image appear on the screen, when I am pressing a button. I have three images which I want to be randomly shown, when I press the button. How do I do this?

If you are using an Array you can use the .randomElement(). Here's a simple example using the symbols from SF Symbols.
struct RandomImage: View {
#State var random: String = ""
var body: some View {
VStack {
Image(systemName: random)
Button(action: {
self.random = chooseRandomImage()
}) {
Text("Another one!")
}
}
}
}
var images = ["sun.max.fill", "moon.fill", "star.fill"]
func chooseRandomImage() -> String {
let array = images
let result = array.randomElement()!
return result
}

Related

How can i import view which bring a closure with itself in SwiftUI? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
Here is my code, it does not work:
struct ContainerView<MyContent: View>: View {
let myContent: () -> MyContent
#State private var myValue: String = ""
var body: some View {
myContent() { value in
myValue = value
}
}
}
I want make this logic works, when I am bringing my view as myContent to body, I want be able to bring a string value with it like in code! I am not looking for reaching my goal with other ways, the goal of this question is be able to access value like in code as clouser.
Warning: I'm not sure what the use-case of this is -- it's not clear what problem is trying to be solved here, but there's likely a better fit that trying to make something like this work. This answer, though, does solve the compilation errors presented above.
Your syntax inside body implies that you want a trailing closure on myContent, but it's not defined in the signature. This would solve the compilation error:
struct ContainerView<MyContent: View>: View {
let myContent: (#escaping (String) -> Void) -> MyContent
#State private var myValue: String = ""
var body: some View {
Text(myValue)
myContent() { value in
myValue = value
}
}
}
Call site:
ContainerView { closure in
Button("Test") {
closure("Value")
}
}

Initialize swift/swiftui var with 3 conditions [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
I am trying to initialize a var with a couple of conditions
struct BreadCrumbCard: View {
var selection:String
var isSelected: Bool
var color = Color("Gray")
if(isSelected){ //error is here
color = Color("Yellow")
}else if(!selection.isEmpty){
color = Color("Green")
}else{
color = Color("Gray")
}
var body: some View{
...
"Expected declaration"
I've been searching for some time now but I can't find a way to do this or an alternative, I'm sure this must be obvious but I am new to swift. How can I initialize this variable with these conditions?
You can't put control code in a struct's or class's top-level scope, it must always be placed inside a function or similar context.
There's several ways to solve this problem, one way would be to use a computed property:
struct BreadCrumbCard: View {
var selection: String
var isSelected: Bool
var color: Color {
if isSelected { //error is here
return Color("Yellow")
} else if !selection.isEmpty {
return Color("Green")
} else {
return Color("Gray")
}
}
var body: some View{
Text("foo").foregroundColor(self.color)
}
}

Can you upload a custom struct to a Firestore using Swift [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I am creating an app where I have a custom struct called Piece. This piece has a string name, a string location, and a map/ dict. Is there a way to save this to Firestore?
Example code but this is what I will need to upload.
struct Piece {
name = 2222
location = "Drawer-1"
quantities = ["blue" : 1, "red" : 3]
}
This is my first post ever so sorry if I do things wrong format-wise.
yes - this is possible. I wrote a long blog post about this: Mapping Firestore Data in Swift - The Comprehensive Guide.
In your case, here is how you would do this:
First, make your struct (and the Quantity struct) codable:
struct Piece: Codable {
#DocumentID var id: String?
var name: Int // are you sure that a field containing a number like 2222 should be called "name"?
var location: String
var quantities: [Quantity]
}
struct Quantity: Codable {
var color: String
var amount: Int
}
Then, create a class for accessing Firestore. You can name it PieceStore or PieceRepository, whatever you like.
class PieceStore {
func addPiece(piece: Piece) {
let collectionRef = db.collection("pieces")
do {
let newDocReference = try collectionRef.addDocument(from: piece)
print("Piece stored with new document reference: \(newDocReference)")
}
catch {
print(error)
}
}
}
See the blog post for more details about fetching data using one-time fetches and snapshot listeners (which will give you that cool real-time sync that Firestore is famous for).

How can I scan and read qr codes in swift UI [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I've searched a lot on this but have only found in UIKit and I am unable to convert this to SwiftUI
There is no specific SwiftUI component for this purpose. But you can embed a UIKit component in a SwiftUI View and use that.
Here is a nice example implementation of that.
https://github.com/twostraws/CodeScanner by Paul Hudson
Example usage also by Paul Hudson:
import CodeScanner
import SwiftUI
struct ContentView: View {
#State private var isShowingScanner = false
var body: some View {
Button(action: {
self.isShowingScanner = true
}) {
Text("Show Scanner")
}
.sheet(isPresented: $isShowingScanner) {
CodeScannerView(codeTypes: [.qr], simulatedData: "Some simulated data", completion: self.handleScan)
}
}
private func handleScan(result: Result<String, CodeScannerView.ScanError>) {
self.isShowingScanner = false
switch result {
case .success(let data):
print("Success with \(data)")
case .failure(let error):
print("Scanning failed \(error)")
}
}
}

Swift - Merging 2 arrays of objects with a key [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm new to Swift programming and been working on an app fir a couple of weeks now, and I'm stuck at a crucial moment in the development.
I'm fetching data from a URL that returns a JSON. It is decoded and the data o is stored in an array.
I do the same thing with another URL.
Now I'm trying to initialize my final object wich will be a combination of 2 objects contained in each of the arrays.
Each array is a dictionary and each objects has a property call id.
I can't figure how I can go through each arrays to check for the id of each objects to match and then initialize a new object by combining the data from each object (look at the code below, it will make more sense hopefully)
I tried a for ... in but I couldn't access the id property and compare it. I tried to do a for ... in inside a for ... in to compare the id value: no success too.
On top of this, the initialization is also a challenge. I tried to implement something like this:
self.mergedList = (//result of the loops).map(MergedViewModel.init)
Here an example of the 2 objects
class MergeInformationViewModel {
var id = "1234"
var information = "This Is My Name"
}
class MergeDataViewModel {
var id = "1234"
var data = "Some very important data"
}
The object I'm trying to initialize
class MergedViewModel {
let mergedViewData: MergeDataViewModel
let mergedViewInformation: MergeInformationViewModel
init(data: MergeDataViewModel, information: MergeInformationViewModel) {
self.mergedViewData = data
self.mergedViewInformation = information
}
var id: String {
return self.mergedViewData.id
}
var information: String {
return self.mergedViewInformation.information
}
var data: String {
return self.mergedViewData.data
}
}
Finally the class handling the initialization. I'm working on a SwiftUI project
class MergedListViewModel: ObservableObject {
init() { mergingAndInit() }
#Published var mergedList = [MergedViewModel]()
var mergeInformationList = [MergeInformationViewModel]()
var mergeDataList = [MergeDataViewModel]()
func mergingAndInit() {
//...
}
}
the final result would look something like this
class MergedViewModel {
var id = "1234"
var information = "This Is My Name"
var data = "Some very important data"
}
How can I implement the func mergingAndInit() into my code?
Thanks in advance.
I figure it out!
for mergedI in mergeInformationList {
for mergedD in mergeDataList {
if mergedI.id == mergedD.id {
self.mergedList.append(MergedViewModel(data: mergedD, information: mergedI))
}
}
}