如何在swift3中创建动态tableView部分?

时间:2017-10-26 11:59:58

标签: arrays uitableview swift3

我正在使用swift3中的完整动态表单,如何根据JSON服务响应数组计数创建多个动态部分。 并且每个部分都有不同的元素。

例如:  JSON响应数组计数3。  每个索引都有不同的元素,基于索引部分来实现  tableview部分。

示例数据:

[
    [
    "action-note",
    "actions-control",
    confirm,
    confirm
],
    [
    "select-conditional",
    select,
    select,
    "action-note",
    "actions-control",
    confirm,
    confirm,
    confirm
],
    [
    "tab-control",
    "action-note",
    "error-text",
    checkbox,
    "actions-control"
    ]
]

1 个答案:

答案 0 :(得分:0)

我要去试一下我认为你在问的东西...你想知道如何制作一个看起来像下面的桌面视图......(UITableview)...但是能够有更多或者根据您返回的JSON,每个部分包含更少的部分和更多或更少的行。

Section 1
  action-note
  actions-control
  confirm
  confirm

Section 2
  select-conditional
  select
  select
  action-note
  actions-control
  confirm
  confirm
  confirm

Section 3
  tab-control
  action-note
  error-text
  checkbox
  actions-control

首先,您需要将JSON内容放入数组数组([[]])。

'[[Section name1, row1, row2, row3, row...n],
  [Section name2, row1, row2, row3, row...n],
  [Section name3, row1, row2, row3, row...n]]' 

UITableview代码如下所示......

class ViewController: UIViewController, UITableViewDelegate, 
UITableViewDataSource  {


let arrOfArrFromJSON= '[["Section 1", "action-note", "actions-control", "confirm", "confirm"],
  ["Section 2", "select-conditional", row2, row3, row...n],
  [Section name3, row1, row2, row3, row...n]]' //Blah blah you can fill the rest of the array out
let cellReuseIdentifier = "cell" //This is your cell identifier that was defined on the storyboard.

override func viewDidLoad() {
    super.viewDidLoad()

}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
 // #warning Incomplete implementation, return the number of sections

    return arrOfArrFromJSON.count //Counting the number of arrays within your array. Or number of sections within your array.

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrOfArrFromJSON[section].count //For each section, it counts the number of rows.
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell! //Your UITableView is called 'tableView' in this example. It could be whatever you defined it as in the storyboard.

    cell.textLabel?.text = arrOfArrFromJSON[indexPath.section][indexPath.row+1] // This will name each row or cell label according to whats in your array of arrays. The +1 is to not start at your section name.

    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("You tapped cell number \(indexPath.row) within section number \(indexPath.section)")//When you click on a cell it will return what cell you pressed in what section.
}

}

我没有测试此代码,因此可能会出现一些语法错误。这应该会让你接近。