C# 中的 kvo(内容大小)
本文关键字:中的 kvo | 更新日期: 2023-09-27 18:30:20
我想翻译这段代码
[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#。(摘自 UITableView 完成请求数据时收到通知?
这就是我走到这一步的方式:
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
}
//}
}
}
我遇到的问题:
- 如何从 NSObject 转换为 NSValue?
- 如何检查 NSValue 是否具有有效值?
- 我拿什么
Action<NSObservedChange> observer
? - 我如何让它工作?
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;
}
看看这个单点触摸样本。