我有一个 UITextView 子类,我在其中添加了一个 NSNotificationCenter 观察器。但是我在哪里再次删除观察者呢?
我的代码:
_textDidChangeNotification = UITextView.Notifications.ObserveTextDidChange(TextDidChange);
在 Objective C 中,我会在 dealloc 方法中执行此操作,但我不确定在 C# 中的何处执行相同操作
据我了解我应该调用的文档
_textDidChangeNotification.Dispose()
我试过
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
_textDidChangeNotification.Dispose();
}
}
但它从未被调用。
完整的类,根据要求:
public class PlaceholderTextView : UITextView
{
public string Placeholder
{
get { return PlaceholderLabel.Text; }
set
{
PlaceholderLabel.Text = value;
PlaceholderLabel.SizeToFit();
}
}
protected UILabel PlaceholderLabel { get; set; }
protected NSObject _textDidChangeNotification;
public override string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
AdjustPlaceholderHidden();
}
}
public PlaceholderTextView()
{
SetupLayout();
_textDidChangeNotification
= UITextView.Notifications.ObserveTextDidChange(TextDidChange);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_textDidChangeNotification.Dispose();
}
protected void SetupLayout()
{
PlaceholderLabel = new UILabel(new CGRect(0, 9, 0, 0));
PlaceholderLabel.TextColor = UIColor.FromWhiteAlpha(0.702f, 1f);
AddSubview(PlaceholderLabel);
}
protected void AdjustPlaceholderHidden()
{
if (Text.Length > 0)
{
PlaceholderLabel.Hidden = true;
}
else
{
PlaceholderLabel.Hidden = false;
}
}
protected void TextDidChange(object sender, Foundation.NSNotificationEventArgs args)
{
AdjustPlaceholderHidden();
}
}
最佳答案
我会在 ViewWillDisappear
中这样做:
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear (animated);
SubscribeMessages ();
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
UnSubscribeMessages ();
}
public void SubscribeMessages ()
{
_hideObserver = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, OnKeyboardNotification);
_showObserver = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, OnKeyboardNotification);
}
public void UnSubscribeMessages ()
{
if (_hideObserver != null) NSNotificationCenter.DefaultCenter.RemoveObserver (_hideObserver);
if (_showObserver != null) NSNotificationCenter.DefaultCenter.RemoveObserver(_showObserver);
}
或 ViewDidDisappear
就像在 Xamarin 示例代码中一样 here
更新 我现在明白你的意思了,我怀疑有什么东西阻止了自定义 View 被垃圾收集。你看过这个blog post吗?这可能会有所帮助。
也来自这个sample code看起来您正在正确调用处置,但它们取消了 ViewDidUnload
上的自定义 View here :
关于c# - 何时何地调用 RemoveObserver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36844026/