如何使用Swift 4.0以编程方式实现UITableView

在本教程中,我将向您展示如何仅使用代码,不使用Storyboard,不使用xib,仅使用代码来创建简单的UITable视图。

让我们潜入……

  1. 打开Xcode并创建一个新的Single View App项目,为其命名为TableView ,单击下一步,将其保存在某个位置,然后单击创建
  2. 在Xcode导航器中删除ViewController.swift。
  3. 在导航器中单击项目名称,转到“常规”选项卡,在“部署信息”下,删除“主要” Storybaord,它应保持空白。
  4. 创建一个新的Swift文件并将其命名为TableViewExample
  5. 将以下代码添加到刚创建的TableViewExample.swift文件中。
导入UIKitclass TableView:UITableViewController { 

让cellId =“ cellId”

覆盖func viewDidLoad(){
super.viewDidLoad()

setupTableView()}

func setupTableView(){
//注册一个用于创建新表单元格的类。
tableView.register(UITableViewCell.self,forCellReuseIdentifier:cellId)

}

}

didFinishLaunchingWithOptions方法中打开AppDelegate.swift 添加以下代码。

 窗口= UIWindow() 
窗口?.makeKeyAndVisible()
window?.rootViewController = TableViewExample()

现在让我们添加那些UITableView委托方法。

打开TableViewExample.swift,然后在文件末尾添加以下扩展名。

 扩展TableView { 

覆盖func numberOfSections(在tableView中:UITableView)-> Int {
返回1
}


覆盖func tableView(_ tableView:UITableView,numberOfRowsInSection部分:Int)-> Int {
返回5
}

覆盖func tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath)-> UITableViewCell {

让cell = tableView.dequeueReusableCell(withIdentifier:cellId,for:indexPath)
cell.textLabel?.text =“世界你好”

返回单元格} }

如果您一直遵循到现在,则可以单击播放按钮或cmd + r运行该应用程序,这将启动模拟器。 您应该得到下面的图像。

官方Github存储库: https : //github.com/YoelL/TableViewExample