Reputation: 1165
I have followed this tutorial for building a text field form inside a table and i've managed to do it but in the tutorial he just uses a single type for the fields. I want some fields to have dropdowns and i'll also add other fields.
I'm not sure of the best way to do this, i'm guessing the fields need to be in an array to make it a lot easier to manage. I was thinking of the code below, the structs are just generic for now.
struct DropdownInput {
let name: String
let placeholder: String
let defaultValue: String
let values: [String]
}
struct TextInput {
let name: String
let placeholder: String
let defaultValue: String
}
var formFields: [Any] = [
TextInput(name: "test1", placeholder: "Some value", defaultValue: ""),
DropdownInput(name: "test2", placeholder: "Some value", defaultValue: "", values: ["Test1","TEST2","Test3"]),
]
Edit: My code is working but I think it's not unpacking the formField object properly. It's saying value of type Any has no member name, how can I access the values?
if self.formFields[indexPath.row] is TextInput {
if let fieldValues: Any = self.formFields[indexPath.row] as? TextInput {
if let cell = tableView.dequeueReusableCellWithIdentifier("cellTextField") as? TextInputTableViewCell {
print(fieldValues.name)
return cell
}
}
}
Upvotes: 0
Views: 80
Reputation: 2294
You can make it a little simple if you have two different cells;
struct TextInput {
let cellIdentifier: String
let name: String
let placeholder: String
let defaultValue: String
let values: [String]
}
var formFields: [TextInput] = [
TextInput(cellIdentifier: "cellTextField", name: "test1", placeholder: "Some value", defaultValue: "", values: []),
TextInput(cellIdentifier: "cellDropdownTextField", name: "test2", placeholder: "Some value", defaultValue: "", values: ["Test1","TEST2","Test3"]),
]
and then;
let txtInput:TextInput = self.formFields[indexPath.row]; //It is not optional, so no if condition.
let cell = tableView.dequeueReusableCellWithIdentifier(txtInput.cellIdentifier, forIndexPath: indexPath) as! UITableViewCell; //It must return cell, if the cell is registered so no if condition here too.
return cell;
Upvotes: 0
Reputation: 1017
Answering your question that "any has no member name" - just remove Any and use
if let fieldValues = formFields[indexPath.row] as? TextInput {
print(fieldValues.name)
}
Upvotes: 1