【问题标题】:KVO of contentSize in C#C#中contentSize的KVO
【发布时间】:2014-11-14 13:27:12
【问题描述】:

我想翻译这段代码

[self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld | NSKeyValueObservingOptionPrior context:NULL];

还有这个

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentSize"]) {
        DLog(@"change = %@", change.description)

        NSValue *new = [change valueForKey:@"new"];
        NSValue *old = [change valueForKey:@"old"];

        if (new && old) {
            if (![old isEqualToValue:new]) {
                // do your stuff
            }
        }
    }
}

到 C#。 (取自Get notified when UITableView has finished asking for data?

这是我到目前为止的方式:

this.TableView.AddObserver ("contentSize", NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old | NSKeyValueObservingOptions.Prior, null);

public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
{
    //base.ObserveValue (keyPath, ofObject, change, context);

    if (keyPath == "contentSize") {
        NSValue newValue = (NSValue)NSValue.FromObject(change["new"]);
        NSValue oldValue = (NSValue)NSValue.FromObject(change["old"]);

        //if (newValue && oldValue) {
            if(!oldValue.IsEqualTo(newValue)){
                // do something here
            }
        //}
    }
}

我遇到的问题:

  1. 如何将 NSObject 转换为 NSValue?
  2. 如何检查 NSValue 是否具有有效值?
  3. Action<NSObservedChange> observer 有什么用?
  4. 我如何让它发挥作用?

【问题讨论】:

    标签: c# uitableview xamarin.ios xamarin key-value-observing


    【解决方案1】:
        void AddObservers()
        {
            TextView.AddObserver(this, "contentSize", NSKeyValueObservingOptions.OldNew, IntPtr.Zero);
        }
    
        public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
        {
            if (keyPath == "contentSize")
                OnSizeChanged(new NSObservedChange(change));
            else
                base.ObserveValue(keyPath, ofObject, change, context);
        }
    
        void OnSizeChanged(NSObservedChange change)
        {
            CGSize oldValue = ((NSValue)change.OldValue).CGSizeValue;
            CGSize newValue = ((NSValue)change.NewValue).CGSizeValue;
    
            var dy = newValue.Height - oldValue.Height;
        }
    

    看看这个monotouch-samples.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      相关资源
      最近更新 更多