I’ve researched this on the site and tutorials, but I can’t find the code to prompt for user input (as an integer) and then insert that integer into an array. Can anyone point me in the right direction or let me know how to code this? Much appreciated.
Are you trying to achieve this with UIKit or SwiftUI?
hello, check out this article we have that talks about arrays in Swift
I’m using SwiftUI - any tips welcome. Thanks
Thanks very much, good info on arrays - but it doesn’t include how to have a numpad pop up to enable user input data into an array.
You might find this useful. Create a new project and paste this in place of your existing ContentView:
struct ContentView: View {
@State private var integerArray = [Int]()
@State private var itemToAdd = ""
@State private var isAddingItem = false
var body: some View {
NavigationView {
VStack {
List {
ForEach(0..<integerArray.count, id: \.self) { item in
Text("\(integerArray[item])")
}
}
if isAddingItem {
Form {
Section(header: Text("Item to Add")) {
HStack {
TextField("Key in value", text: $itemToAdd)
.keyboardType(.numberPad)
Button(action: {
addItem()
}) {
Text("Done")
}
}
}
}
.frame(height: 100)
}
}
.listStyle(PlainListStyle())
.navigationTitle("Integer Array")
.navigationBarItems(
trailing:
Button(action: {
isAddingItem = true
}) {
Image(systemName: "plus")
.padding(5)
}
)
}
}
func addItem() {
if itemToAdd != "" {
integerArray.append(Int(itemToAdd)!)
itemToAdd = ""
}
isAddingItem = false
}
}
The “Done” button is added since the number pad does not have an Enter, Return or Done button by default.