Note that the word "graph" here means a graph theory graph, not a statistical graph.
I am trying to create a graph that has nodes that you can move around on the screen. I decided to use a custom UIView
subclass - NodeView
to represent the nodes. To make it moveable, I used the CocoaPod SEDraggable.
I decided that the whole graph would be drawn by another custom UIView
called GraphView
. This class has a graph
property and when set, it will draw the whole graph by first removing the subviews from the previous graph (if any) and then adding new NodeView
s. Then I will call setNeedsDisplay
which will in turn call draw(_:)
.
In the overridden draw
method, I will draw the lines (edges, in graph theory jargon) between the nodes.
Now I need to detect that a node has been moved. When they has been moved, I need to call setNeedsDisplay
to redraw the lines. I looked around and understood that this can be done with KVO. However, my graph view needs to be able to display a graph with an arbitrary number of nodes. This means that I will put my nodes into an array. According to this post, KVOing an array is not possible.
Then I tried to use NSNotificationCenter
but I soon found out that there is no notification for when a view gets moved from this post.
Then I found this post but the OP uses KVO which can't be used in my case for aforementioned reasons. Also, that post is in Objective-C which I can't understand very well.
How can I create a graph like that? Am I going in the right direction? Or is there a trick that I can use that does not involve redrawing everything when the nodes are moved? I feel like redrawing the whole graph every frame will be slow.