简体   繁体   English

如何在Swift中填充表格视图?

[英]How to fill a Table View in Swift?

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" 第1行“一个”第2行“两个”

But how can I fill the TableView not at the beginning of my program but anytime else? 但是,如何不在程序开始时而是在其他任何时间填充TableView? I tried to call the methods below in an other function that viewDidLoad but it doest't work... why? 我试图在另一个函数viewDidLoad中调用下面的方法,但是它不起作用...为什么?

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. 用户搜索后,它包含一些BLE设备。

表视图具有一个reloadData方法,该方法可以执行您想要的操作。

Its very simple 非常简单

  1. Update your data in your array 更新数组中的数据
  2. Then reload your tableview by using your_tableview.reloadData() 然后使用your_tableview.reloadData()重新加载表格视图

Ex: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM