问题描述
我有一个连接IBOutlet的 UIView
对象(innerView),它位于视图控制器( UIViewController
)的视图上方.我想让用户用手指旋转innerView.因此,我将 UIView
的子类(TouchView)设置为innerView的类.当用户旋转视图对象时,我希望视图控制器从TouchView接收一个值.而我所拥有的如下.
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
}
}
好吧,视图控制器从不接收来自TouchView的委托调用.我究竟做错了什么?谢谢您的帮助.
Well, the view controller never receives a delegate call from TouchView. What am I doing wrong? Thank you for your help.
推荐答案
我看到2个问题
- 您创建了touchView的新实例,但未将其添加到视图控制器的视图中
- 您的innerView不是touchView的实例,并且未设置其委托
我对您情况的处理方式如下:
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
}
}
这篇关于使用委托将数据从UIView子类发送到UIViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!