ios Swift 的 UITableView 示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33234180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:03:04  来源:igfitidea点击:

UITableView example for Swift

iosswiftuitableview

提问by Suragch

I've been working with Swift and iOS for a number of months now. I am familiar with many of the ways things are done but I'm not good enough that I can just write things up without looking. I've appreciated Stack Overflow in the past for providing quick answers to get me back on track with topics I've gotten rusty on (for example, AsyncTask Android example).

几个月来,我一直在使用 Swift 和 iOS。我熟悉许多做事的方式,但我不够好,我可以不看就写出来。我很欣赏 Stack Overflow 过去提供的快速答案,让我回到我已经生疏的主题(例如,AsyncTask Android 示例)的轨道上。

iOS's UITableViewis in this category for me. I've done them a few times, but I forget what the details are. I couldn't find another question on StackOverflow that just asks for a basic example and I'm looking for something shorter than many of the tutorials that are online (although this oneis very good).

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

I am providing an answer below for my future reference and yours.

我在下面提供了一个答案,以供将来参考和您的参考。

回答by Suragch

The example below is an adaptation and simplification of a longer postfrom We ? Swift. This is what it will look like:

下面的例子是一个适应和简化较长后从我们?迅速。这是它的样子:

enter image description here

在此处输入图片说明

Create a New Project

创建新项目

It can be just the usual Single View Application.

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

Add the Code

添加代码

Replace the ViewController.swiftcode with the following:

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

Read the in-code comments to see what is happening. The highlights are

阅读代码中的注释以了解发生了什么。亮点是

  • The view controller adopts the UITableViewDelegateand UITableViewDataSourceprotocols.
  • The numberOfRowsInSectionmethod determines how many rows there will be in the table view.
  • The cellForRowAtIndexPathmethod sets up each row.
  • The didSelectRowAtIndexPathmethod is called every time a row is tapped.
  • 视图控制器采用UITableViewDelegateUITableViewDataSource协议。
  • numberOfRowsInSection方法确定表视图中将有多少行。
  • cellForRowAtIndexPath方法设置每一行。
  • didSelectRowAtIndexPath每次点击一行时都会调用该方法。

Add a Table View to the Storyboard

将表视图添加到故事板

Drag a UITableViewonto your View Controller. Use auto layout to pin the four sides.

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

enter image description here

在此处输入图片说明

Hook up the Outlets

连接奥特莱斯

Controldrag from the Table View in IB to the tableViewoutlet in the code.

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

Finished

完成的

That's all. You should be able run your app now.

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

This answer was tested with Xcode 9 and Swift 4

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



Variations

变化

Row Deletion

行删除

You only have to add a single method to the basic project above if you want to enable users to delete rows. See this basic exampleto learn how.

如果您想让用户删除行,您只需在上面的基本项目中添加一个方法。请参阅此基本示例以了解如何操作。

enter image description here

在此处输入图片说明

Row Spacing

行间距

If you would like to have spacing between your rows, see this supplemental example.

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

enter image description here

在此处输入图片说明

Custom cells

自定义单元格

The default layout for the table view cells may not be what you need. Check out this exampleto help get you started making your own custom cells.

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

enter image description here

在此处输入图片说明

Dynamic Cell Height

动态单元格高度

Sometimes you don't want every cell to be the same height. Starting with iOS 8 it is easy to automatically set the height depending on the cell content. See this examplefor everything you need to get you started.

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

enter image description here

在此处输入图片说明

Further Reading

进一步阅读

回答by Matt Le Fleur

For completeness sake, and for those that do not wish to use the Interface Builder, here's a way of creating the same table as in Suragch's answerentirely programatically - albeit with a different size and position.

为了完整起见,对于那些不希望使用界面生成器的人,这里有一种完全以编程方式创建与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).")
    }

}

Make sure you have remembered to import UIKit.

确保你已经记住了import UIKit

回答by iOS

In Swift 4.1 and Xcode 9.4.1

在 Swift 4.1 和 Xcode 9.4.1 中

  1. Add UITableViewDataSource, UITableViewDelegate delegated to your class.

  2. Create table view variable and array.

  3. In viewDidLoad create table view.

  4. Call table view delegates

  5. Call table view delegate functions based on your requirement.

  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
}

If you are using storyboard, no need for Step 3.

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

But you need to create IBOutlet for your table view before Step 4.

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

回答by Ananda Aiwale

//    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;
        }
}

回答by Ahmet Akk?k

Here is the Swift 4 version.

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

}