我正在嘗試在 iPhone 的原生天氣應用程式中重新創建類似的東西,您可以在其中選擇多個位置,并將它們作為 TableViews 附加到帶有 UIPageControl 的 UIScrollView
我從二維陣列中的硬編碼模型開始。我希望每個陣列進入每個 tableView,總共五個 tableView,第一個 tableView 中有一行,第二個中有兩個,等等:
var model: [[String]] = [
["TableView 1: row 1"],
["TableView 2: row 1", "TableView 2: row 2"],
["TableView 3: row 1", "TableView 3: row 2", "TableView 3: row 3"],
["TableView 4: row 1", "TableView 4: row 2", "TableView 4: row 3", "TableView 4: row 4"],
["TableView 5: row 1", "TableView 5: row 2", "TableView 5: row 3", "TableView 5: row 4", "TableView 5: row 5"]
]
現在我只能圍繞一些非常簡單的東西,如下所示,這樣第一個 tableView 有 5 個單元格,上面寫著“TableView 1”,然后第二個有五個單元格,上面寫著“TableView 2”,依此類推:
//number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
//cell for row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
for i in 0...model.count-1{
//grab the correct tableView from the array of tableViews
if tableView == self.tableViews[i]{
//dequeue the cell using a nib
let cell = tableView.dequeueReusableCell(withIdentifier: ProtoTypeTableViewCell.identifier, for: indexPath) as! ProtoTypeTableViewCell
//set text for the label in the nib file
cell.label.text = "TableView \(i 1)"
return cell
}
}
return UITableViewCell()
}
任何幫助將不勝感激; 謝謝。
uj5u.com熱心網友回復:
這對我來說是一個非常有趣的問題,因為我確實喜歡重新創建流行應用程式的 UI。我認為有幾種方法可以實作這一目標,我將向您展示一種方法。
我認為要解決的主要挑戰:
- 用于設定的最佳 UI 組件
- 將正確的模型從二維陣列映射到正確的表格視圖
對于 UI 組件,我選擇了這種方式:
- 分頁 UIScrollView
- UIStackView 包含在 Paging UIScrollView 中
- UIStackView 中包含的 UITableView
- UIStackView 包含在 Paging UIScrollView 中
這是我如何去做這件事并添加評論來解釋
最初設定
class PagingTableView: UIViewController
{
// Same model as yours
var model: [[String]] = [
["TableView 1: row 1"],
["TableView 2: row 1",
"TableView 2: row 2"],
["TableView 3: row 1",
"TableView 3: row 2",
"TableView 3: row 3"],
["TableView 4: row 1",
"TableView 4: row 2",
"TableView 4: row 3",
"TableView 4: row 4"],
["TableView 5: row 1",
"TableView 5: row 2",
"TableView 5: row 3",
"TableView 5: row 4",
"TableView 5: row 5"]
]
let scrollView: UIScrollView =
{
let scrollView = UIScrollView()
scrollView.isPagingEnabled = true
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
let stackView: UIStackView =
{
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.distribution = .equalSpacing
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
let pageControl = UIPageControl()
let padding: CGFloat = 20
let pageWidth = UIScreen.main.bounds.width
let tableViewCellIdentifier = "cell"
// Use this factor to unique identify your table
let tableViewUniqueIdFactor = 1000
// https://stackoverflow.com/a/21130486/1619193
// You can ignore this function, created for convenience
private func randomColor() -> UIColor
{
let red = CGFloat(arc4random_uniform(256)) / 255.0
let blue = CGFloat(arc4random_uniform(256)) / 255.0
let green = CGFloat(arc4random_uniform(256)) / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
override func viewDidLoad()
{
super.viewDidLoad()
title = "Paging TableView"
view.backgroundColor = .white
// Configure everything, functions come later
configureScrollViewLayout()
configureStackViewLayout()
configurePageControl()
addTableViewsToStackView()
}
配置滾動視圖布局
private func configureScrollViewLayout()
{
scrollView.delegate = self
view.addSubview(scrollView)
// Auto layout
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
.isActive = true
scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,
constant: padding).isActive = true
scrollView.widthAnchor.constraint(equalToConstant: pageWidth).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,
constant: -padding * 3).isActive = true
}
配置您的堆疊視圖布局
private func configureStackViewLayout()
{
scrollView.addSubview(stackView)
// Auto layout
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor)
.isActive = true
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor)
.isActive = true
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor)
.isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor)
.isActive = true
stackView.heightAnchor.constraint(equalTo: scrollView.heightAnchor,
multiplier: 1).isActive = true
}
配置頁面控制元件布局
private func configurePageControl()
{
pageControl.numberOfPages = model.count
pageControl.currentPage = 0
pageControl.tintColor = randomColor()
pageControl.pageIndicatorTintColor = randomColor()
pageControl.currentPageIndicatorTintColor = randomColor()
view.addSubview(pageControl)
// Auto layout
pageControl.translatesAutoresizingMaskIntoConstraints = false
pageControl.centerXAnchor.constraint(equalTo: view.centerXAnchor)
.isActive = true
pageControl.topAnchor.constraint(equalTo: scrollView.bottomAnchor)
.isActive = true
pageControl.widthAnchor.constraint(equalToConstant: 200)
.isActive = true
pageControl.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
.isActive = true
}
配置表視圖并將其添加到堆疊視圖
private func addTableViewsToStackView()
{
for modelIndex in 0 ..< model.count
{
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
// Uniquely identify each table which will come in handy
// when figuring out which model should be loaded for a specific
// table view
tableView.tag = tableViewUniqueIdFactor modelIndex
// Register a default UITableView Cell
tableView.register(UITableViewCell.self,
forCellReuseIdentifier: tableViewCellIdentifier)
tableView.dataSource = self
tableView.backgroundColor = randomColor()
// remove additional rows
tableView.tableFooterView = UIView()
stackView.addArrangedSubview(tableView)
tableView.widthAnchor.constraint(equalToConstant: pageWidth)
.isActive = true
// height is calculated automatically based on the height
// of the stack view
}
}
// end of the class PagingTableView
}
在這個階段,如果你運行它,你將運行應用程式,你會看到設定就像天氣應用程式一樣,其中沒有資料,分頁控制元件尚未連接,但我們的頁面數量與模型相同(5):

現在剩下的是將頁面控制元件和表格視圖連接到模型
使用滾動視圖委托更新頁面視圖
extension PagingTableView: UIScrollViewDelegate
{
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)
{
// Make sure you don't do anything with table view scrolls
// This is only a worry if the view controller is the table view's
// delegate also
if !(scrollView is UITableView)
{
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
}
}
實作表視圖資料源,將表映射到模型
extension PagingTableView: UITableViewDataSource
{
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int
{
// Retrieve the correct model using the unique identifier created earlier
let modelIndex = tableView.tag - tableViewUniqueIdFactor
// Get the correct array needed from model
let modelForeCurrentTable = model[modelIndex]
return modelForeCurrentTable.count
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellIdentifier)!
// Retrieve the correct model using the unique identifier created earlier
let modelIndex = tableView.tag - tableViewUniqueIdFactor
// Get the correct array needed from model
let modelForeCurrentTable = model[modelIndex]
cell.textLabel?.text = modelForeCurrentTable[indexPath.row]
cell.backgroundColor = .clear
return cell
}
}
現在一切都設定好了,你會得到類似于天氣應用程式的東西,每個表格視圖中都會顯示正確的資料,并且頁面控制元件也已連接:

最后的評論
You can skip the layout parts if you create your UI using frames or in storyboard. I tried to give you something from start to finish that you would run in isolation and you could play around with it by tweaking things.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427940.html
