【发布时间】:2016-04-25 14:50:51
【问题描述】:
我有一个 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();
}
}
【问题讨论】:
标签: c# xamarin xamarin.ios nsnotificationcenter