How to fill a Table View in Swift?

杀马特。学长 韩版系。学妹 提交于 2020-01-14 05:25:08

问题


I have written this code:

//Basic methods
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.DevicesTableView.registerClass(UITableViewCell.self,forCellReuseIdentifier: "cell")
    self.DevicesTableView.dataSource = self

}


var array = ["one","two"]

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return array.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell: UITableViewCell! = self.DevicesTableView
        .dequeueReusableCellWithIdentifier("cell") as UITableViewCell!

    cell.textLabel!.text = self.array[indexPath.row]

    return cell
}

So the code works pretty well and shows me the tableview filled with:

Row1 "One" Row2 "Two"

But how can I fill the TableView not at the beginning of my program but anytime else? I tried to call the methods below in an other function that viewDidLoad but it doest't work... why?

self.DevicesTableView.registerClass(UITableViewCell.self,forCellReuseIdentifier: "cell") self.DevicesTableView.dataSource = self

EDIT:

I would like to display an array which isn't initialized at the beginning of my program. It contains some BLE devices after the user searched for them.


回答1:


Its very simple

  1. Update your data in your array
  2. Then reload your tableview by using your_tableview.reloadData()

Ex:

var array = ["one","two","Three","Four"] // your array will take no.of.row in section
DevicesTableView.reloadData()



回答2:


Table views have a reloadData method which does what you want.



来源:https://stackoverflow.com/questions/32799098/how-to-fill-a-table-view-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!