2016-04-26 27 views
0

drawRect:を使用して図形を描画しています。私はこのメソッドを呼び出して、方向が変わったときに形状を再描画する必要があります。が呼び出されたときに自動的にdrawRect:を呼び出す方法があると思いました。drawRectを呼び出す方法:layoutSubviewsがiosで呼び出すとき

ありがとうございます。それだ

This method is called when a view is first displayed or when an event occurs that invalidates a visible part of the view. You should never call this method directly yourself. To invalidate part of your view, and thus cause that portion to be redrawn, call the setNeedsDisplay or setNeedsDisplayInRect: method instead.

:UIViewクラスの参照https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instm/UIView/drawRectから

答えて

2

だけで設定ビューのcontentModeUIViewContentModeRedrawへ。

これはsetNeedsDisplay(したがってdrawRect)たびビューの境界の変更を起動しますので、また(ビューの境界は、回転に変更するようにセットアップあなたのautoresizingMaskをした提供)回転時に呼び出されます。

+0

私が 'init:'に 'contentMode'を設定しても動作しないのですが、代わりに他の方法で設定する必要がありますか? –

+0

@SunilRaoあなたの 'init'は呼び出されていますか(ブレークポイントを設定しますか?ほとんどの場合、 'UIView'サブクラスでは、' init'の代わりに 'initWithFrame:'をオーバーライドする必要があります.' init'の 'UIView'実装は' initWithFrame:CGRectZero'を呼び出すだけです。また、 'autoresizingMask'をチェックして、回転時にビューの境界(幅または高さ)を変更することを確認してください。そして、いいえ、一定の一回限りの設定であるため、初期化子に 'contentMode'を設定する必要があります。 – Hamish

+0

それは完璧に機能しました。 –

2

。適切なビューでsetNeedsDisplayに電話するだけです。

NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated", name: UIDeviceOrientationDidChangeNotification, object: nil) 

をして、次の関数を追加します:のviewDidLoadで

+0

私は 'drawRect:'から 'setNeedsDisplay'を呼び出すと、この警告が出ます** _ BSMachError:(os/kern)無効な機能(20)**および** _ BSMachError:(os/kern)invalid name(15) ** –

+0

これは明らかに無限ループを引き起こす 'drawRect:'が呼び出されることを示しています。あなたは 'layoutSubviews'からそれを呼びたいと思ったのですか? –

+0

ああ!うん、もし 'layoutSubviews()'から呼び出されたら、私の悪い、タイプミス! –

0

は()関数は入れ

func rotated() 
{ 
    if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)) 
    {    
     print("landscape") 
     // Your drawRect function here 
    } 

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)) 
    { 
     print("Portrait") 
     // Your drawRect function here 

    } 

} 
関連する問題