KVO不工作(swift 2.2)?

时间:2016-08-04 13:13:37

标签: swift key-value-observing

  • 在我的应用程序中,OneVC是PageViewController的子ViewControllers之一,TwoVC是OneVC容器视图的嵌入视图控制器。
  • 当用户在OneVC中拖动滚动视图时,我希望拖动操作不仅可以从Web API更新OneVC中的内容,还可以通知TwoVC更新。
  • 启动时,OneVC和TwoVC都会同时出现在界面上。

我正在关注Apple的“使用Swift with Cocoa和Objective-C”“Key-Value Observing”指令来暗示KVO,但是当观察到的属性发生变化时,不会发送任何通知。请参阅下面的代码:

  

OneVC是要观察的对象。

public class HueWheel : Slider
{
    static HueWheel()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(HueWheel), new FrameworkPropertyMetadata(typeof(HueWheel)));
    }

    private bool _isPressed = false;
    private Canvas _PART_FirstCanvas;
    private Canvas _PART_SecondCanvas;

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        //  Use () cast rather than the "as" operator because if the actual runtime 
        //  type can't be cast to the desired type, that'll throw an exception 
        //  rather than silently returning null. If you had cast (Ellipse)e.Source, 
        //  that would have blown up on you because you can't cast HueWheel to Ellipse. 
        //  That would have instantly shown you what was wrong. 
        //  But you won't get an exception here if GetTemplateChild() just returns null. 
        _PART_FirstCanvas = (Canvas)GetTemplateChild("PART_FirstCanvas");
        _PART_SecondCanvas = (Canvas)GetTemplateChild("PART_SecondCanvas");
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        if (_isPressed)
        {
            const double RADIUS = 150;

            //  Or _PART_SecondCanvas; whichever. 
            Point newPos = e.GetPosition(_PART_FirstCanvas);

            double angle = MyHelper.GetAngleR(newPos, RADIUS);
            //huewheel.Value = (huewheel.Maximum - huewheel.Minimum) * angle / (2 * Math.PI);
        }
    }

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        _isPressed = true;
    }

    protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
    {
        _isPressed = false;
    }
}
  

TwoVC是观察者

class OneVC: UIViewController, UIScrollViewDelegate {
 dynamic var isDragToUpdate = false

 func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if scrollView.contentOffset.y < -150 {         
        if isDragToUpdate {
            isDragToUpdate = false
        } else {
            isDragToUpdate = true
        }

        print(isDragToUpdate)
    }
 }
}

我逐行检查,发现了很多其他stackoverflow的答案,但仍然不知道我的代码出了什么问题,当拖动并释放滚动视图时,“hoh”和“hah”都没有在控制台中打印,除了打印(isDragToUpdate)打印得当。

提前谢谢!

0 个答案:

没有答案