Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift的UITableView示例_Ios_Swift_Uitableview - Fatal编程技术网

Ios Swift的UITableView示例

Ios Swift的UITableView示例,ios,swift,uitableview,Ios,Swift,Uitableview,我已经和Swift和iOS合作好几个月了。我对很多事情的处理方式都很熟悉,但我还不够好,不需要看就可以把事情写下来。过去,我很欣赏堆栈溢出,因为它提供了快速的答案,让我回到了我已经生疏的主题的轨道上(例如,) iOS的UITableView对我来说属于这一类。我做过几次,但我忘了细节是什么。我找不到关于StackOverflow的其他问题,它只要求提供一个基本的示例,我正在寻找比许多在线教程更短的内容(尽管非常好) 我在下面提供了一个答案,供我和你将来参考。下面的例子是我们对❤ 敏捷的这就是它的

我已经和Swift和iOS合作好几个月了。我对很多事情的处理方式都很熟悉,但我还不够好,不需要看就可以把事情写下来。过去,我很欣赏堆栈溢出,因为它提供了快速的答案,让我回到了我已经生疏的主题的轨道上(例如,)

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


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

下面的例子是我们对❤ 敏捷的这就是它的样子:

创建新项目 它可以只是普通的单视图应用程序

添加代码 将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).")
    }
}
阅读代码中的注释以查看发生了什么。亮点是

  • 视图控制器采用
    UITableViewDelegate
    UITableViewDataSource
    协议
  • numberofrowsinssection
    方法确定表视图中将有多少行
  • cellforrowatinexpath
    方法设置每一行
  • 每次点击一行时都会调用
    didSelectRowAtIndexPath
    方法
将表视图添加到情节提要 将
UITableView
拖到视图控制器上。使用“自动布局”固定四边

连接插座 控制从IB中的表视图到代码中的
tableView
出口的拖动

完成了 就这些。你现在应该可以运行你的应用了

这个答案用Xcode 9和Swift 4进行了测试


变化 行删除

如果要使用户能够删除行,只需向上面的基本项目添加一个方法。看看如何学习

行间距

如果希望在行之间设置间距,请参见

自定义单元格

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

动态单元格高度

有时你不希望每个细胞都有相同的高度。从iOS 8开始,可以轻松地根据单元格内容自动设置高度。为你所需要的一切,让你开始

进一步阅读

为完整起见,对于那些不希望使用Interface Builder的用户,这里提供了一种完全以编程方式创建相同表格的方法—尽管大小和位置不同

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

}

确保您已记住导入UIKit

这是Swift 4版本

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

}

在Swift 4.1和Xcode 9.4.1中

  • 添加委派给类的UITableViewDataSource、UITableViewDelegate

  • 创建表视图变量和数组

  • 在viewDidLoad中创建表视图

  • 调用表视图代理

  • 根据需要调用表视图委托函数

  • 如果您使用的是故事板,则无需执行步骤3


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

    如果您可以添加让表视图填充屏幕所需的代码,那就太好了。目前,它只占据了您硬编码的矩形。@ChrisGillum、.tableView.registerClass已更改为tableView.register,供有疑问的人注册。TODO:添加/链接到静态表视图示例精彩的答案!我还将添加一些其他常见功能,例如通过在viewDidLoad()中添加页脚
    tableview.tableFooterView=UIView()
    ,添加
    cell.imageView!来消除空的tableview行!。image=UIImage(名为:“image”)
    用于行图标图像,而
    cell.backgroundColor=UIColor
    用于cell background,您是否可以添加一些解释,说明这与其他答案有何不同?供将来参考:这是一个简化版本-它包含表视图的最小值。这就是区别所在。这里有一个带说明的教程。不到10分钟,一步一步。
    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
    }