make a drag function for a rectangle that returns the string "yellow" in swift in swift

You can create a draggable UIView that represents your rectangle and add a pan gesture recognizer to it. Here's an example implementation that returns "yellow" when the view is dragged:

main.swift
class DraggableView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupGestureRecognizers()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupGestureRecognizers()
    }
    
    private func setupGestureRecognizers() {
        let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
        addGestureRecognizer(panGestureRecognizer)
    }
    
    @objc private func handlePanGesture(_ gestureRecognizer: UIPanGestureRecognizer) {
        switch gestureRecognizer.state {
        case .changed:
            let translation = gestureRecognizer.translation(in: self.superview)
            center = CGPoint(x: center.x + translation.x, y: center.y + translation.y)
            gestureRecognizer.setTranslation(.zero, in: self.superview)
        case .ended:
            // You can specify your custom condition to return the output here
            // For example, if the view is dropped in a specific area of the screen
            return "yellow"
        default:
            break
        }
    }
    
}
1155 chars
34 lines

You can then use the DraggableView in your view controller like this:

main.swift
class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let draggableView = DraggableView(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
        draggableView.backgroundColor = .yellow
        view.addSubview(draggableView)
    }
    
}
313 chars
12 lines

Now, when you drag the view around and drop it in the specified area, the function will return "yellow".

related categories

gistlibby LogSnag