回転の通知を各UIViewで受け取る
回転の通知を各UIViewで受け取るには例えば
public class UITextField2 : UITextField { private NSObject deviceRotateNotification; public UITextField2 () { deviceRotateNotification = NSNotificationCenter.DefaultCenter.AddObserver (UIDevice.OrientationDidChangeNotification, DidChangeOrientation); } private void DidChangeOrientation (NSNotification notification) { if (UIDevice.CurrentDevice.Orientation == UIDeviceOrientation.Portrait || UIDevice.CurrentDevice.Orientation == UIDeviceOrientation.PortraitUpsideDown) { // なにか } else { // なにか } } }
このようにすればDidChangeOrientationメソッドが呼ばれるようになる。
だが気になる点が一つ。
このUIViewのインスタンスが消滅するときにdeviceRotateNotificationはどうなるんだろう。
NSNotificationCenter.DefaultCenter.RemoveObserverしなくてもいいんだろうか。
そもそもこの方法に間違いがあるのではないだろうか。
追記1
WillMoveToSuperviewとRemoveFromSuperviewを使うようにしてみた。
public override void WillMoveToSuperview (UIView newsuper) { base.WillMoveToSuperview (newsuper); if (newsuper != null) deviceRotateNotification = NSNotificationCenter.DefaultCenter.AddObserver (UIDevice.OrientationDidChangeNotification, DidChangeOrientation); } public override void RemoveFromSuperview () { base.RemoveFromSuperview (); if (deviceRotateNotification != null) { NSNotificationCenter.DefaultCenter.RemoveObserver (deviceRotateNotification); } }
この方法だとViewがいらなくなったときに明示的にRemoveFromSuperviewしてもらわないといけない。これは例えば親のUIVIewがRemoveFromSuperviewされると破綻する。汎用的ではない。
追記2
DisposeでRemoveObserverするようにしたがいつまでたっても呼ばれない。これはなにかどこかViewを掴んだままになっているのかもしれない。これはこれで問題だ。