Goal Example
- The user clicks 1st circle button and 2nd circle button
- Then the line will draw from 1st to 2nd
- NOTE: Button is movable
What've tried
- There are two
Heart
inBoardView
. Each heart hasMovableCard
- When
Heart
is tapped, then notify and pass self
struct Heart: View {
var body: some View {
MovableCard("heart.fill")
.onTapGesture {
// Notify this card is tapped
NotificationCenter.default.post(heartOnTap, ["self":self])
}
}
}
- There is viewModel in BoardView that observes
heartOnTap
struct BoardView: View {
@StateObject var viewModel = ViewModel()
var body: some View {
ZStack{
Heart()
Heart()
Path{ path in
path.move(to: viewModel.firstCard.POS ?? CGPoint(x: -1, y: -1))
path.addLine(to: viewModel.secondCard.POS ?? CGPoint(x: -1, y: -1))
}
}
}
}
ViewModel
will listenheartOnTap
for receivingHeart: View
- I send
Heart: View
not the tap position because it's movable. - But
Heart
that conformedView
doesn't have any access for directly getting its position
class ViewModel: ObservableObject {
@Published var firstCard: Heart?
@Published var secondCard: Heart?
init() {
NotificationCenter.default.addObserver(self,
selector: #selector(self.didTap(_:)),
name: heartOnTap,
object: nil)
}
@objc func didTap(_ notification: NSNotification) {
guard let heart = notification.userInfo?["self"] as? Heart else { return }
if firstCard == nil {
firstCard = HEARTPOSITION // <- Heart position for drawing the line
}
if secondCard == nil {
secondCard = HEARTPOSITION // <- Heart position for drawing the line
}
}
}
Discussion
Is there a possible solution for drawing line from view to another view. (view is movable)
Alternative Goal