Swift 的 UITableView 示例 [英] UITableView example for Swift

查看:29
本文介绍了Swift 的 UITableView 示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Swift 和 iOS 已经有几个月了.我熟悉许多做事的方式,但我不够好,我可以不看就写出来.我很欣赏 Stack Overflow 过去提供的快速答案,让我回到我已经生疏的主题(例如,

创建一个新项目

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

添加代码

ViewController.swift 代码替换为以下内容:

导入 UIKit类视图控制器:UIViewController、UITableViewDelegate、UITableViewDataSource {//数据模型:这些字符串将是表格视图单元格的数据让动物:[String] = [马"、牛"、骆驼"、羊"、山羊"]//单元格重用id(滚动出视图的单元格可以重用)let cellReuseIdentifier = "cell";//不要忘记从故事板中连接它@IBOutlet var tableView:UITableView!覆盖 func viewDidLoad() {super.viewDidLoad()//注册表格视图单元格类和它的重用idself.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)//(可选)如果要删除多余的空单元格分隔线,请包含此行//self.tableView.tableFooterView = UIView()//此视图控制器本身将为表视图提供委托方法和行数据.tableView.delegate = selftableView.dataSource = self}//表格视图中的行数func tableView(_ tableView: UITableView, numberOfRowsInSection 部分: Int) ->整数{返回 self.animals.count}//为每个表格视图行创建一个单元格func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell {//如果需要,创建一个新单元格或重用旧单元格让 cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) 作为 UITableViewCell!//设置数据模型中的文本cell.textLabel?.text = self.animals[indexPath.row]返回单元格}//点击表格视图单元格时运行的方法func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {打印(您点击了单元格编号(indexPath.row).")}}

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

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

将表视图添加到故事板

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

连接奥特莱斯

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

完成

仅此而已.您现在应该可以运行您的应用了.

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


变化

行删除

如果你想让用户删除行,你只需要在上面的基本项目中添加一个方法.请参阅

行距

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

自定义单元格

表格视图单元格的默认布局可能不是您所需要的.

动态单元格高度

有时您不希望每个单元格都具有相同的高度.从 iOS 8 开始,很容易根据单元格内容自动设置高度.

进一步阅读

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

iOS's UITableView is 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 one is very good).

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

解决方案

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

Create a New Project

It can be just the usual Single View Application.

Add the Code

Replace the ViewController.swift code with the following:

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 UITableViewDelegate and UITableViewDataSource protocols.
  • The numberOfRowsInSection method determines how many rows there will be in the table view.
  • The cellForRowAtIndexPath method sets up each row.
  • The didSelectRowAtIndexPath method is called every time a row is tapped.

Add a Table View to the Storyboard

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

Hook up the Outlets

Control drag from the Table View in IB to the tableView outlet in the code.

Finished

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

This answer was tested with Xcode 9 and 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 example to learn how.

Row Spacing

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

Custom cells

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

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 example for everything you need to get you started.

Further Reading

这篇关于Swift 的 UITableView 示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆