Sending Data to UIViewController From UIView Subclass With Delegate

回眸只為那壹抹淺笑 提交于 2021-02-05 08:22:27

问题


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.


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/41007529/sending-data-to-uiviewcontroller-from-uiview-subclass-with-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!