Skip to content

Commit

Permalink
feat: GesturePublisher 생성
Browse files Browse the repository at this point in the history
  • Loading branch information
MaraMincho committed Jan 11, 2024
1 parent 11e8928 commit 13caa50
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
38 changes: 38 additions & 0 deletions iOS/Projects/Shared/CombineCocoa/Sources/GestureSubscription.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
//
// GestureSubscription.swift
// CombineCocoa
//
// Created by MaraMincho on 1/11/24.
// Copyright © 2024 kr.codesquad.boostcamp8. All rights reserved.
//

import Combine
import UIKit

final class GestureSubscription<T: Subscriber>: Subscription where T.Input == UIGestureRecognizer, T.Failure == Never {
var subscriber: T?
let gesture: UIGestureRecognizer
var targetView: UIView?

@objc func action() {
_ = subscriber?.receive(gesture)
}

init(subscriber: T, gesture: UIGestureRecognizer, targetView: UIView) {
self.subscriber = subscriber
self.gesture = gesture
self.targetView = targetView

gesture.addTarget(self, action: #selector(action))
targetView.addGestureRecognizer(gesture)
}

func request(_: Subscribers.Demand) {}

func cancel() {
gesture.removeTarget(self, action: #selector(action))
targetView?.removeGestureRecognizer(gesture)
targetView = nil
subscriber = nil
}
}
59 changes: 59 additions & 0 deletions iOS/Projects/Shared/CombineCocoa/Sources/UIView+Publisher.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//
// UIView+Publisher.swift
// CombineCocoa
//
// Created by MaraMincho on 1/11/24.
// Copyright © 2024 kr.codesquad.boostcamp8. All rights reserved.
//

import Combine
import UIKit

public extension UIView {
func publisher(gesture: GestureType) -> GesturePublisher {
return GesturePublisher(targetView: self, gesture: gesture.recognizer)
}

struct GesturePublisher: Publisher {
public typealias Output = UIGestureRecognizer
public typealias Failure = Never

let targetView: UIView
let gesture: UIGestureRecognizer
init(targetView: UIView, gesture: UIGestureRecognizer) {
self.targetView = targetView
self.gesture = gesture
}

public func receive<S>(subscriber: S) where S: Subscriber, Never == S.Failure, UIGestureRecognizer == S.Input {
let subscription = GestureSubscription(subscriber: subscriber, gesture: gesture, targetView: targetView)
subscriber.receive(subscription: subscription)
}
}

enum GestureType {
case tap
case swipe
case longPress
case pan
case pinch
case edge

var recognizer: UIGestureRecognizer {
switch self {
case .tap:
return UITapGestureRecognizer()
case .swipe:
return UISwipeGestureRecognizer()
case .longPress:
return UILongPressGestureRecognizer()
case .pan:
return UIPanGestureRecognizer()
case .pinch:
return UIPinchGestureRecognizer()
case .edge:
return UIPinchGestureRecognizer()
}
}
}
}

0 comments on commit 13caa50

Please sign in to comment.