Skip to content

Commit 5900a5c

Browse files
committed
refactor: refactor a funct tableView to use SwiftUI
Replace a bit of Cocoa code with SfiwtUI to show how it reduces code size, and can be refactored incrementally.
1 parent 72b5fa1 commit 5900a5c

File tree

2 files changed

+14
-23
lines changed

2 files changed

+14
-23
lines changed

Makefile

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ all: $(DIST_DIR)/$(BINARY_NAME)
99

1010
$(DIST_DIR)/$(BINARY_NAME): $(SRC_DIR)/main.swift
1111
@mkdir -p $(DIST_DIR)
12-
swiftc -O -o $(DIST_DIR)/$(BINARY_NAME) $(SRC_DIR)/main.swift -framework Cocoa
12+
swiftc -O -o $(DIST_DIR)/$(BINARY_NAME) \
13+
$(SRC_DIR)/main.swift \
14+
-framework Cocoa \
15+
-framework SwiftUI
1316

1417
install: $(DIST_DIR)/$(BINARY_NAME)
1518
@echo "Installing to $(PREFIX)/bin..."

src/main.swift

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
import Cocoa
1111
import Darwin
12+
import SwiftUI
1213

1314
/// A custom table row view that provides hover and selection effects
1415
class HoverTableRowView: NSTableRowView {
@@ -507,28 +508,15 @@ class MenuApp: NSObject, NSApplicationDelegate, NSTableViewDataSource, NSTableVi
507508
/// - row: The row for which to provide the view
508509
/// - Returns: The view to display in the table cell
509510
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
510-
let cellPadding: CGFloat = 4
511-
let cell = NSTextField(labelWithString: filteredItems[row])
512-
cell.textColor = NSColor.white
513-
cell.backgroundColor = NSColor.clear
514-
cell.isBordered = false
515-
cell.font = NSFont.systemFont(ofSize: 16, weight: .regular)
516-
cell.lineBreakMode = .byTruncatingTail
517-
518-
// Create container for proper padding and hover state
519-
let container = NSView(frame: NSRect(x: 0, y: 0, width: tableView.frame.width, height: tableView.rowHeight))
520-
container.wantsLayer = true
521-
522-
// Center the cell vertically in its container and add side padding
523-
let cellHeight = cell.cell?.cellSize.height ?? 20
524-
let yOffset = (container.frame.height - cellHeight) / 2
525-
cell.frame = NSRect(x: cellPadding,
526-
y: yOffset,
527-
width: container.frame.width - (cellPadding * 2),
528-
height: cellHeight)
529-
530-
container.addSubview(cell)
531-
return container
511+
let text = filteredItems[row]
512+
let hostingView = NSHostingView(rootView:
513+
Text(text)
514+
.font(.system(size: 16, weight: .regular))
515+
.foregroundColor(.white)
516+
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
517+
.padding(.leading, 4)
518+
)
519+
return hostingView
532520
}
533521

534522
/// Provides a custom row view for the table

0 commit comments

Comments
 (0)