使用Delegate从UIView子类向UIViewController发送数据

时间:2016-12-07 00:43:45

标签: ios swift uiview uiviewcontroller swift3

我有一个IBOutlet连接的UIView对象(innerView)坐在视图控制器(UIViewController)的视图上。我想让用户用手指旋转innerView。所以我有一个UIView的子类(TouchView)设置为innerView的类。当用户旋转视图对象时,我希望视图控制器从TouchView接收值。我所拥有的是以下内容。

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

好吧,视图控制器永远不会从TouchView接收委托调用。我究竟做错了什么?谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

我看到了2个问题

  1. 您创建了一个新的touchView实例,但未将其添加到视图控制器的视图中
  2. 您的innerView不是touchView的实例,其代理未设置
  3. 我对你情况的处理方式如下:

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