我有一个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)); 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上清空了自定义视图:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。