简体   繁体   English

如何调用drawRect:当layoutSubviews在iOS中调用时

[英]How to invoke drawRect: when layoutSubviews invokes in ios

I am using drawRect: to draw shapes. 我正在使用drawRect:绘制形状。 I have to invoke this method and redraw the shapes when orientation changes, so i thought if there is a way to invoke drawRect: automatically when layoutSubviews() been called. 我必须调用此方法并在方向更改时重新绘制形状,所以我认为是否有一种方法可以在调用layoutSubviews()时自动调用drawRect:

Thank you. 谢谢。

You can set the view's contentMode to .redraw . 您可以将视图的contentMode设置为.redraw

This will invoke setNeedsDisplay (and therefore drawRect ) whenever the view's bounds change, and will therefore also be invoked upon rotation (provided you've setup your autoresizingMask so that the view's bounds change on rotation). 每当视图的边界发生变化时,这将调用setNeedsDisplay (并因此调用drawRect ),因此也将在旋转时被调用(前提是您已设置autoresizingMask以便视图的边界在旋转时发生变化)。

From the UIView class reference https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instm/UIView/drawRect : 从UIView类参考https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instm/UIView/drawRect

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. 要使视图的一部分无效,从而使该部分重绘,请改为调用setNeedsDisplay或setNeedsDisplayInRect:方法。

That's it. 而已。 Just call setNeedsDisplay on the appropriate view. 只需在适当的视图上调用setNeedsDisplay

In viewDidLoad() function put: 在viewDidLoad()函数中输入:

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

and then add the following function: 然后添加以下功能:

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

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

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM