【问题标题】:UITableView example for SwiftSwift 的 UITableView 示例
【发布时间】:2016-01-18 23:12:06
【问题描述】:

我已经使用 Swift 和 iOS 工作了几个月了。我熟悉许多事情的完成方式,但我还不够好,我可以不看就写出来。过去,我很感谢 Stack Overflow 提供的快速答案,让我回到了我已经生疏的主题的正轨(例如,AsyncTask Android example)。

iOS 的UITableView 对我来说属于这一类。我已经做了几次,但我忘记了细节是什么。我在 StackOverflow 上找不到另一个仅要求提供基本示例的问题,我正在寻找比许多在线教程更短的内容(尽管 this one 非常好)。

我在下面提供一个答案,以供我和你的未来参考。

【问题讨论】:

标签: ios swift xcode uitableview cocoa-touch


【解决方案1】:

下面的例子是对来自 We ❤ Swift 的a longer post 的改编和简化。这就是它的样子:

创建一个新项目

它可以只是普通的单视图应用程序。

添加代码

用以下代码替换 ViewController.swift 代码:

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    // Data model: These strings will be the data for the table view cells
    let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    
    // cell reuse id (cells that scroll out of view can be reused)
    let cellReuseIdentifier = "cell"
    
    // don't forget to hook this up from the storyboard
    @IBOutlet var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Register the table view cell class and its reuse id
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
        
        // (optional) include this line if you want to remove the extra empty cell divider lines
        // self.tableView.tableFooterView = UIView()

        // This view controller itself will provide the delegate methods and row data for the table view.
        tableView.delegate = self
        tableView.dataSource = self
    }
    
    // number of rows in table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.animals.count
    }
    
    // create a cell for each table view row
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // create a new cell if needed or reuse an old one
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
        
        // set the text from the data model
        cell.textLabel?.text = self.animals[indexPath.row]
        
        return cell
    }
    
    // method to run when table view cell is tapped
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }
}

阅读代码内的 cmets 以了解发生了什么。亮点是

  • 视图控制器采用UITableViewDelegateUITableViewDataSource协议。
  • numberOfRowsInSection 方法确定表格视图中有多少行。
  • cellForRowAtIndexPath 方法设置每一行。
  • 每次点击一行时都会调用didSelectRowAtIndexPath 方法。

向情节提要添加表格视图

UITableView 拖到您的视图控制器上。使用自动布局固定四个边。

连接奥特莱斯

Control 从 IB 中的 Table View 拖动到代码中的 tableView 出口。

完成

就是这样。您现在应该可以运行您的应用了。

这个答案已经用 Xcode 9 和 Swift 4 测试过


变化

行删除

如果你想让用户删除行,你只需要在上面的基本项目中添加一个方法。请参阅this basic example 了解如何操作。

行间距

如果您希望行之间有间距,请参阅this supplemental example

自定义单元格

表格视图单元格的默认布局可能不是您需要的。 Check out this example 帮助您开始制作自己的自定义单元格。

动态单元格高度

有时您不希望每个单元格都具有相同的高度。从 iOS 8 开始,很容易根据单元格内容自动设置高度。 See this example 为您提供入门所需的一切。

进一步阅读

【讨论】:

  • TODO:添加/链接到静态表视图示例
  • 精彩的答案!我还将添加一些其他常见功能,例如通过在 viewDidLoad() 中添加页脚 tableView.tableFooterView = UIView() 来消除空的 tableview 行,为行图标图像添加 cell.imageView!.image = UIImage(named: "image"),为单元格背景添加 cell.backgroundColor = UIColor
【解决方案2】:

为了完整起见,对于那些不希望使用 Interface Builder 的人,这里有一种完全以编程方式创建与 Suragch's answer 相同的表的方法 - 尽管大小和位置不同。

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

    var tableView: UITableView = UITableView()
    let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    let cellReuseIdentifier = "cell"

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.frame = CGRectMake(0, 50, 320, 200)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

        self.view.addSubview(tableView)
    }

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

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

        cell.textLabel?.text = animals[indexPath.row]

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }

}

确保您记得import UIKit

【讨论】:

【解决方案3】:

在 Swift 4.1 和 Xcode 9.4.1 中

  1. 添加 UITableViewDataSource、UITableViewDelegate 委托给你的类。

  2. 创建表视图变量和数组。

  3. 在 viewDidLoad 创建表视图。

  4. 调用表视图委托

  5. 根据您的要求调用表视图委托函数。

import UIKit
// 1
class yourViewController: UIViewController , UITableViewDataSource, UITableViewDelegate { 

// 2
var yourTableView:UITableView = UITableView()
let myArray = ["row 1", "row 2", "row 3", "row 4"]

override func viewDidLoad() {
    super.viewDidLoad()

    // 3
    yourTableView.frame = CGRect(x: 10, y: 10, width: view.frame.width-20, height: view.frame.height-200)
    self.view.addSubview(yourTableView)

    // 4
    yourTableView.dataSource = self
    yourTableView.delegate = self

}

// 5
// MARK - UITableView Delegates
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return myArray.count
}

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

var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
    }
    if self. myArray.count > 0 {
        cell?.textLabel!.text = self. myArray[indexPath.row]
    }
    cell?.textLabel?.numberOfLines = 0

    return cell!
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return 50.0
}

如果您正在使用情节提要,则无需执行第 3 步。

但您需要在第 4 步之前为您的表格视图创建 IBOutlet。

【讨论】:

    【解决方案4】:

    SWIFT 5

    如果您只想在屏幕上显示一个 tableView,那么您可以将 UITableViewController 实现到您的 ViewController 并这样做以显示一个简单的带有标签的 tableViewController

    Swift 文件

    class ToDoListViewController: UITableViewController {
        let array = ["GAFDGSG","VSBFFSB","BFBFB"]
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            array.count
        }
        
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath)
            cell.textLabel?.text = array[indexPath.row]
            return cell
        }
        override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            print(indexPath)
        }
    }
    

    然后在情节提要中创建一个 UITableViewController 并提及这样的标识符

    主线故事板

    结果

    【讨论】:

      【解决方案5】:

      这是 Swift 4 版本。

      import Foundation
      import UIKit
      
      class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
      { 
          var tableView: UITableView = UITableView()
          let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
          let cellReuseIdentifier = "cell"
      
          override func viewDidLoad()
          {
              super.viewDidLoad()
      
              tableView.frame = CGRect(x: 0, y: 50, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
              tableView.delegate = self
              tableView.dataSource = self
              tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
      
              self.view.addSubview(tableView)
          }
      
          func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
          {
              return animals.count
          }
      
          internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
          {
              let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
      
              cell.textLabel?.text = animals[indexPath.row]
      
              return cell
          }
      
          private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath)
          {
              print("You tapped cell number \(indexPath.row).")
          }
      
      }
      

      【讨论】:

        【解决方案6】:
        //    UITableViewCell set Identify "Cell"
        //    UITableView Name is  tableReport
        
        UIViewController,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        
            @IBOutlet weak var tableReport: UITableView!  
        
            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                    return 5;
                }
        
                func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                    let cell = tableReport.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
                    cell.textLabel?.text = "Report Name"
                    return cell;
                }
        }
        

        【讨论】:

        • 您能否添加一些解释,说明这与其他答案有何不同?
        • 供将来参考:这是一个简化版本 - 它包含最少的表格视图。这就是区别。m
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-24
        相关资源
        最近更新 更多