Swift的UITableView示例 [英] UITableView example for Swift
问题描述
我已经和Swift和iOS合作了好几个月了。我熟悉许多方法已经完成,但我不够好,我只能在不看的情况下写出来。我很欣赏Stack Overflow过去提供的快速答案,让我回到正轨,我已经生锈了(例如,
创建新项目
它可以是通常的单一视图应用程序。
添加代码
用以下内容替换 ViewController.swift 代码:
import UIKit
class ViewController:UIViewController,UITableViewDelegate,UITableViewDataSource {
//数据模型:这些字符串将是表视图单元格的数据
let animals:[String ] = [马,牛,骆驼,羊,山羊]
//单元格重用ID(滚出视图的单元格可以重复使用)
让cellReuseIdentifier =cell
//不要忘记从故事板中挂钩这个
@IBOutlet var tableView:UITableView!
覆盖func viewDidLoad(){
super.viewDidLoad()
//注册表视图单元类及其重用ID
self.tableView .register(UITableViewCell.self,forCellReuseIdentifier:cellReuseIdentifier)
//(可选)如果要删除额外的空单元格分隔线,则包含此行
// self.tableView.tableFooterView = UIView()
//这个视图控制器本身将为表视图提供委托方法和行数据。
tableView.delegate = self
tableView.dataSource = self
}
//表视图中的行数
func tableView(_ tableView:UITableView ,numberOfRowsInSection section:Int) - > Int {
return self.animals.count
}
//为每个表视图行创建一个单元格
func tableView(_ tableView:UITableView,cellForRowAt indexPath: IndexPath) - > UITableViewCell {
//如果需要创建一个新单元格或重用旧单元
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier:cellReuseIdentifier)作为UITableViewCell!
//设置数据模型中的文本
cell.textLabel?.text = self.animals [indexPath.row]
return cell
}
//点击表视图单元格时运行的方法
func tableView(_ tableView:UITableView,didSelectRowAt indexPath:IndexPath){
print(你点击单元格号码\\ \\(indexPath.row)。)
}
}
阅读代码内注释,看看发生了什么。亮点是
- 视图控制器采用
UITableViewDelegate
和UITableViewDataSource
protocols。 -
numberOfRowsInSection
方法确定表视图中将有多少行。 -
cellForRowAtIndexPath
方法设置每一行。 -
每次点击一行时都会调用didSelectRowAtIndexPath
方法。
将表格视图添加到故事板 h1>
将 UITableView
拖到View Controller上。使用自动布局固定四边。
连接奥特莱斯
控制从IB中的表格视图拖动到 tableView
代码中的插座。
已完成
这就是全部。你现在应该可以运行你的应用了。
这个答案是用Xcode 9和Swift 4测试的
变化
行删除
如果要允许用户删除行,您只需要在上面的基本项目中添加一个方法。请参阅
行间距
如果你愿意的话想要在行之间留出间距,请参阅
自定义单元格
表视图单元格的默认布局可能不是您所需要的。
动态单元格高度
有时您不希望每个单元格都具有相同的高度。从iOS 8开始,可以根据单元格内容自动设置高度。
进一步阅读
- 创建表格视图(Apple Docs教程) )
- Ray Wenderlich教程
- iOS& Swift教程:UITableViewController
- 使用Swift的iOS表格视图教程
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
andUITableViewDataSource
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
- Create a Table View (Apple Docs tutorial)
- Ray Wenderlich tutorials
- iOS & Swift Tutorial: UITableViewController
- iOS Table View Tutorial Using Swift
这篇关于Swift的UITableView示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!