标签:c nsnotificationcenter xamarin-ios xamarin
我有一个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);
}
或者像Xamarin示例代码here中的ViewDidDis似
更新
我明白你的意思了,我怀疑某些事情阻止了自定义视图被垃圾收集.你有没有看过这个blog post可能会有所帮助.
同样从这个sample code看起来你正在调用dispose但是它们在ViewDidUnload here上清空了自定义视图:
标签:c,nsnotificationcenter,xamarin-ios,xamarin 来源: https://codeday.me/bug/20190711/1431129.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。