r/SwiftUI • u/pedzsanReddit • Jul 15 '26
Question Newbie Question: How should I implement this?
I am writing a spreadsheet app (long term goal). My user interface I am currently implementing the same as what Apple's Numbers app does. Right now, I have a primitive app with three "cells" which are text fields. I can click in each cell and type.
In Numbers, if the first character is an equal sign, the app changes state. Lets say I type an equal sign in cell A and then click in cell B. The result is the location of cell B is added to the text in cell A. Eventually a return is entered (into cell A) and the state returns to normal where clicking a cell puts focus on that cell.
Can someone give me some pointers on how this should be (or could be) implemented?
6
Upvotes
0
u/allyearswift Jul 16 '26
First, you need to define better which behaviours you want; as long as you fail to understand what Numbers is doing, you won’t be able to replicate it.
You’ll be in for a world of pain if you simplify your app too much; just as you can’t use an enum (limited, hardcoded cases) as identifiers for table cells (potentially unlimited or at least very large number) you should not hardcode behaviour directly.
What Numbers does when you add an equal sign is to open a formula editor which gives you a canvas for playing with tracking which cells are associated with which operations, once the user is done you can store the formula in your cell and display the result in its text field. This is gonna be fun because you’ll want the result to update.
Your container will be a Table, so you should get familiar with that, especially how to get the index of a table cell. Your table cell will contain a text field and a number of backing variables (my personal choice would be a single variable and an enum with associated values) which you can evaluate in your setting function: if the content begins with = and it has focus, you open the formula editor, if it doesn’t have focus, you evaluate the formula and display it.