This repository was archived by the owner on Jan 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathShoppingListApp.swift
More file actions
110 lines (83 loc) · 2.75 KB
/
Copy pathShoppingListApp.swift
File metadata and controls
110 lines (83 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import WatchKit
//
// Our main interface controller
//
class ShoppingListApp: WKInterfaceController {
@IBOutlet weak var table: WKInterfaceTable!
var items = sampleShoppingList()
// MARK: Initialization
override func awake(withContext context: Any?) {
updateView()
}
var firstActivation = true
override func willActivate() {
if firstActivation {
DispatchQueue.main.async {
self.loadMore()
}
}
firstActivation = false
}
// MARK: Data manipulation
@IBAction func add() {
items.insert(sampleShoppingItem(), at: random(items.count))
rowLimit += 1
updateView()
}
@IBAction func changeUp() {
items = shoppingListVariation(items)
updateView()
}
// MARK: Rendering
var displayedRows: [ShoppingItemRowModel] = []
func updateView() {
let newRows = items.limit(rowLimit).map { ShoppingItemRowModel($0) }
table.updateViewModels(from: displayedRows, to: newRows)
displayedRows = newRows
updateLoadMoreButton()
}
// MARK: Lazy loading
@IBOutlet weak var _loadMoreButton: WKInterfaceButton!
lazy var loadMoreButton: WKUpdatableButton = WKUpdatableButton(self._loadMoreButton, defaultHidden: false)
// This is a tiny number for demonstration only. You'd probably want the initial row limit
// to be ~4 (enough to fit one screen), and in loadMore() — double that number.
var rowLimit = 1
@IBAction func loadMore() {
rowLimit += 1
updateView()
}
func updateLoadMoreButton() {
let moreToLoad = items.count > rowLimit
loadMoreButton.updateHidden(!moreToLoad)
}
}
//
// The view model that describes table row
//
struct ShoppingItemRowModel: TableRowModel {
typealias RowController = ShoppingItemRow
static let tableRowType = "item"
let objectId: String
var name: String
var completed: Bool
init(_ item: ShoppingItem) {
objectId = item.id
name = item.name
completed = item.completed
}
}
//
// The table row controller
//
class ShoppingItemRow: NSObject, UpdatableRowController {
@IBOutlet weak var checkbox: WKInterfaceImage!
@IBOutlet weak var name: WKInterfaceLabel!
func update(from old: ShoppingItemRowModel?, to new: ShoppingItemRowModel) {
checkbox.updateImageName(from: (old?.completed).map(checkboxImage) ?? "checkbox",
to: checkboxImage(new.completed))
name.updateText(from: old?.name, to: new.name)
}
func checkboxImage(_ completed: Bool) -> String {
return completed ? "checkbox-completed" : "checkbox"
}
}