不要試圖用任何單一視圖做太多事情,即使是UICollectionView
。
您顯示的屏幕有UITabBarController
管理其頂級安排。當前選定的選項卡(「主頁」)有一個UINavigationController
管理其內容。
導航堆棧的頂部可能是集合視圖或表視圖。這兩者都可以在這裏使用,因爲這些元素在視覺上佈局爲堆棧中的屏幕寬度的行。表格視圖更簡單,因爲您不必擔心設置佈局。
表視圖有幾個可見行,每個不同:
- 標題/圖像行(「易海鮮飯」)
- 收視率排
- 出口行(心/保存/股)
- 的註釋行
- 創作者行(我假設,因爲它看起來像它可能是一個爆頭和名稱)
而且在視野外可能還有更多獨特的行。
在您的故事板中,您可以將每個行設計爲表視圖控制器場景中的原型行。或者,您可以使用靜態內容行來設計表視圖,如果您不需要在運行時更改行的順序或重複任何行,則更容易。
「但是羅布,」你說,「我不能將所有這些行放入我的故事板的表格視圖中!」Make the storyboard scene taller. UIKit將在運行時調整它的大小以適應設備屏幕。
在每一行中,拖入並安排該行所需數據的子視圖。例如,標題/圖像行需要UIImageView
和UILabel
。評級行需要標籤,可能是自定義視圖來顯示和編輯星星,也可能是佈局的堆棧視圖。
對於每一行,您需要一個單獨的子類UITableViewCell
,並在該行的視圖中指定插座。將數據傳遞到用於顯示每個單元,使得每個單元符合協議:
然後,在你的表視圖控制器,將其設置這樣如果你使用靜態內容:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
if let user = cell as? RecipeUsing {
user.recipe = recipe
}
return cell
}
您將需要一個RecipeTitleImageCell
與網點UIImageView
和UILabel
。事情是這樣的:
class RecipeTitleImageCell: UITableViewCell, RecipeUsing {
@IBOutlet var label: UILabel!
// UITableViewCell has an imageView property that's not an outlet
@IBOutlet var myImageView: UIImageView!
var recipe: Recipe? {
didSet {
guard let recipe = recipe else { return }
label.text = recipe.title
myImageView.image = recipe.image
}
}
}
而對於收視率排,你會想是這樣的:
class RecipeRatingsCell: UITableViewCell, RecipeUsing {
@IBOutlet var ratingControl: RatingControl!
@IBOutlet var label: UILabel!
var recipe: Recipe? {
didSet {
guard let recipe = recipe else { return }
ratingControl.rating = recipe.ratings.reduce(0, +)/recipe.Double(ratings.count)
if ratings.count < 5 { label.text = "Too few ratings" }
else { label.text = "\(ratings.count) ratings" }
}
}
}
謝謝你的這個答案,因爲它給了我的方式接近我的目標更好的主意。我實際上看過這個帖子:https://medium.com/ios-os-x-development/ios-how-to-build-a-table-view-with-multiple-cell-types-2df91a206429它使用與您所建議的類似方法(除了使用nib文件而不使用原型單元格),並且能夠複製作者所展示的內容。我只想問一下。如果我要創建一個根據數據進行調整的行。即配方中的步數。這仍然是一個靜態細胞? – Chace