如何用 Swift 在 UITableView 中插入新行?


要在 UITableView 中插入新行,我们首先要创建一个表格视图行,然后使用表格视图的“Cell for row at”方法将其添加到表格视图。

我们可以使用 Storyboard 创建行,或者创建 UITableViewCell 类的 nib。

在视图控制器中拖放一个表格视图,并将其 outlet 连接到 ViewController 类。

在我们刚才创建的表格视图中创建一个行并创建它的类,称其为 CustomCell,并将类分配给该行。

为其提供标识符“CustomCell”

在单元格中添加一个标签,将其更改为“CustomCell”,以便我们可以识别它,并将其垂直和水平放置在中间。

向我们的类添加以下代码

func numberOfSections(in tableView: UITableView) −> Int {
   return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) −> Int {
   return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) −> UITableViewCell {
   let cell = tblView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
   return cell
}

当我们运行此代码时,它在设备上看起来是这样的。

更新于: 07-30-2019

977 次浏览

开始您的 职业生涯

完成课程,获得认证

开始学习
广告
© . All rights reserved.