我有一个json文件,我正在尝试从其中快速创建3页动态文件,我已使用Codable将json数据传递到模型中,并且可以打印它。这个JSON有3个页面,我想应该是3个UIViewController。我似乎很困惑,如何创建这种动态形式。这是我到目前为止尝试过的
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
guard let data = stubbedResponse("forms") else {return}
do {
let decoded = try JSONDecoder().decode(BaseModel.self, from: data)
print(decoded)
} catch {
}
}
func stubbedResponse(_ filename: String) -> Data! {
@objc class VC: NSObject {}
let bundle = Bundle(for: VC.self)
let path = bundle.path(forResource: filename, ofType: "json")
return (try? Data(contentsOf: URL(fileURLWithPath: path!)))
}
}
JSON:
{
"id": "form_1",
"name": "Pet Adoption Application Form",
"pages": [
{
"label": "Page 1",
"sections": [
{
"label": "Welcome to Pets Rescue",
"elements": [
{
"type": "embeddedphoto",
"file": "https://images.pexels.com/photos/8700/wall-animal-dog-pet.jpg?cs=srgb&dl=animal-collar-dog-8700.jpg&fm=jpg",
"unique_id": "embeddedphoto_1",
"rules": []
}
]
},
{
"label": "Basic Info",
"elements": [
{
"type": "text",
"label": "Your fullname",
"isMandatory": true,
"unique_id": "text_1",
"rules": []
},
{
"type": "text",
"label": "Email address",
"isMandatory": true,
"unique_id": "text_2",
"rules": []
},
{
"type": "formattednumeric",
"label": "Phone Number",
"keyboard": "numeric",
"formattedNumeric": "####-###-####",
"isMandatory": true,
"unique_id": "formattednumeric_1",
"rules": []
},
{
"type": "datetime",
"mode": "date",
"label": "Date of Birth",
"isMandatory": true,
"unique_id": "datetime_1",
"rules": []
}
]
}
]
},
{
"label": "Page 2",
"sections": [
{
"label": "About your home",
"elements": [
{
"type": "yesno",
"label": "Do you have a yard?",
"isMandatory": true,
"unique_id": "yesno_1",
"rules": [
{
"condition": "equals",
"value": "Yes",
"action": "show",
"otherwise": "hide",
"targets": [
"text_3"
]
}
]
},
{
"type": "text",
"label": "Is it fenced? Also indicate the type",
"isMandatory": false,
"unique_id": "text_3",
"rules": []
}
]
}
]
},
{
"label": "Page 3",
"sections": [
{
"label": "Additional Information",
"elements": [
{
"type": "text",
"label": "Please provide your veterinarian's name",
"isMandatory": false,
"unique_id": "text_4",
"rules": []
},
{
"type": "text",
"label": "Please provide the name of a personal reference",
"isMandatory": true,
"unique_id": "text_5",
"rules": []
}
]
}
]
}
]
}
我知道tableView也可以在此实例中使用带有表示下一页的按钮
答案 0 :(得分:0)
您具有这种结构
struct BaseModel {
let pages: [Model]
}
您将拥有一个应递归显示的vc
class SomeVC:UIViewController {
var currentIndex = 0
var pages = [Model]()
}
如果您说有一个结构化的tableView,则在下一页操作中
let next = currentIndex + 1
if next < pages.count {
let vc = SomeVC()
vc.currentIndex = next
vc.pages = pages
// push the vc
}
else {
// no more
}
此外,您还可以选择将此数组设置为单例