El Tomato
El Tomato

Reputation: 6707

Sending Data to UIViewController From UIView Subclass With Delegate

I have an IBOutlet-connected UIView object (innerView) sitting over view controller (UIViewController)'s view. I want to let the user rotate innerView with their finger. So I have a subclass (TouchView) of UIView set to innerView's class. As the user rotates the view object, I want the view controller to receive a value from TouchView. And what I have is the following.

// UIView
protocol TouchDelegate: class {
    func degreeChanged(degree: Double)
}

class TouchView: UIView {
    weak var delegate: TouchDelegate? = nil
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let aTouch: AnyObject = touches.first! as UITouch
        let newLoc = aTouch.location(in: self.superview)

        ...
        ...

        let degree = { (radians: Double) -> Double in
            return radians * 180 / M_PI
        }
        self.delegate?.degreeChanged(degree: degree)
    }
}

// UIViewController
class ViewController: UIViewController, TouchDelegate {
    @IBOutlet weak var innerView: UIView!

    // MARK: - View
    override func viewDidLoad() {
        super.viewDidLoad()
        let touchView = TouchView()
        touchView.delegate = self
    }

    // MARK: - From TouchView
    func degreeChanged(degree: Double) {
        print(degree) // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< no call
    }
}

Well, the view controller never receives a delegate call from TouchView. What am I doing wrong? Thank you for your help.

Upvotes: 1

Views: 808

Answers (1)

Ben Ong
Ben Ong

Reputation: 931

I see 2 problems

  1. You created a new instance of touchView and did not add it into your view controller's views
  2. Your innerView is not an instance of touchView and its delegate is not set

My approach to your situation would look something like this:

// UIViewController
class ViewController: UIViewController, TouchDelegate {
@IBOutlet weak var innerView: TouchView!

// MARK: - View
override func viewDidLoad() {
    super.viewDidLoad()
    innerView.delegate = self
}

    // MARK: - From TouchView
    func degreeChanged(degree: Double) {
        print(degree) // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< no call
    }
}

Upvotes: 2

Related Questions