Swift的UITableView示例

Sur*_*gch 59 uitableview ios swift

我已经和Swift和iOS合作了好几个月了.我熟悉许多方法,但我不够好,我可以不用看就写出来.我很欣赏Stack Overflow过去提供的快速答案,让我回到正轨,我已经生锈了(例如,AsyncTask Android示例).

iOS UITableView对我来说属于这一类.我已经完成了几次,但我忘记了细节.我在StackOverflow上找不到另一个问题,只是要求一个基本的例子,我正在寻找比许多在线教程更短的东西(虽然这个非常好).

我将在下面提供一个答案供我将来参考和你的.

Sur*_*gch 179

以下示例是对We❤Swift 的较长帖子的改编和简化.这就是它的样子:

在此输入图像描述

创建一个新项目

它可以只是通常的单视图应用程序.

添加代码

用以下内容替换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).")
    }
}
Run Code Online (Sandbox Code Playgroud)

阅读代码内注释以了解正在发生的事情.亮点是

  • 视图控制器采用UITableViewDelegateUITableViewDataSource协议.
  • numberOfRowsInSection方法确定表视图中将有多少行.
  • cellForRowAtIndexPath方法设置每一行.
  • didSelectRowAtIndexPath每次轻敲一行时都会调用该方法.

将表视图添加到故事板

将a UITableView拖到View Controller上.使用自动布局固定四个边.

在此输入图像描述

连接奥特莱斯

Control从IB中的表视图拖动到tableView代码中的插座.

成品

就这样.您应该可以立即运行您的应用程序.

这个答案是用Xcode 9和Swift 4测试的


变化

行删除

如果要允许用户删除行,则只需向上面的基本项目添加单个方法.请参阅此基本示例以了解具体方法.

在此输入图像描述

行间距

如果您希望行之间有间距,请参阅此补充示例.

在此输入图像描述

定制单元格

表视图单元格的默认布局可能不是您所需要的.查看此示例以帮助您开始制作自己的自定义单元格.

在此输入图像描述

动态细胞高度

有时您不希望每个单元格都具有相同的高度.从iOS 8开始,可以根据单元格内容自动设置高度.有关开始使用所需的一切,请参阅此示例.

在此输入图像描述

进一步阅读

  • 精彩的回答!我还将添加一些其他常见功能,例如通过在 viewDidLoad() 中添加页脚 `tableView.tableFooterView = UIView()`,添加 `cell.imageView!.image = UIImage(named: "image")` 来消除空的 tableview 行行图标图像,和单元格背景的`cell.backgroundColor = UIColor` (2认同)

Mat*_*eur 23

为了完整起见,以及那些不希望使用Interface Builder的人,这里有一种方法可以完全以编程方式创建与Suragch的答案相同的表- 尽管具有不同的大小和位置.

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).")
    }

}
Run Code Online (Sandbox Code Playgroud)

确保你记得import UIKit.

  • @ChrisGillum,[以下是您将以编程方式添加约束的方式](http://stackoverflow.com/a/36263784/3681880). (3认同)

iOS*_*iOS 11

在 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
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是故事板,则不需要步骤 3。

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


归档时间:

查看次数:

135673 次

最近记录:

6 年,4 月 前