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

How to invoke drawRect: when layoutSubviews invokes in ios

我正在使用 drawRect: 来绘制形状。我必须调用此方法并在方向更改时重新绘制形状,所以我想是否有一种方法可以在调用 layoutSubviews() 时自动调用 drawRect:

谢谢。

来自 UIView class 参考 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

在viewDidLoad()函数中放入:

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

然后添加如下函数:

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

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

    }

}

您可以将视图的 contentMode 设置为 .redraw

每当视图的边界发生变化时,这将调用 setNeedsDisplay(因此 drawRect),因此也会在旋转时调用(前提是您已设置 autoresizingMask 以便视图的边界在旋转时发生变化)。