While working on my toy project; making a memo app, I came across an interesting way to display both text and images in one view at once. Surely, it’s not about how to use
Hstack well. It’s about using lists of generic type.
First of all, you should note that I’m not really trying to make an app 100% identical to Notion at least this time. What I meant from notion-like features is just texts edited line by line and images added by pressing a button like the Notion. I should apologize to the guys who imagined features like draggable texts and buttons with various items like the real Notion app 😥.
Anyway, let’s start from making an array available for generic type.
How to make array of generics
We can do this by using
protocol which is introduced in here. However, I prefer to the way using
enum because it’s easier to handle.
First, I’m going to name each editable block as
Container and kind of parent file containing the containers as
Document. After that, I created an
enum that defines type of containers. In the
enum, I defined the text and image containers which return the contents requested by the view. It will be done by calling computed variables
You also can see the
ImageContainer. Those are the parts that actully contain informations and used to help
enum becoming visible view. I just gave them default values like
“Hello, Wolrd!” or
systemImage:“sparkles” in this case. Of course you can fix it later.
Doucumentstruct has array containing
Container. By creating
enum as we did, we can easily make an array which can save several types of variable. Theoritically, it is also possible to have an array store all kinds of variables. Anyway, those variables(
containers) will be used later to create
Make enum to real view
By using function which converts
enum to view, we can easily make and use the view the way we did before.
ContainerViews, I added some details which make the containers look better.
Connect DocumentView to the main view
I used Swift’s original
List style to make list view of
Documents. The thing you should notice is I’m using
ImagePickerView at line 49. I already made this view referencing this article and you can see the
ImagePickerView parts in my attached Github repo. Nothing special here other than using
onChange. You may be able to understand the codes easily.
After all doing this, you can get the same result as the GIF I attached below which I already attached once.
This one wasn’t that difficult. However, many of the desired features have not been implemented yet, so I will discuss this further in the next post. For example, click to edit or delete, or drag a block to move it.