redraw a custom uiview when changing a device orientation
Go here to learn how to receive notifications for when the device orientation changes. When the orientation does change, just call [chartView setNeedsDisplay];
to make drawRect:
get called so you can update your view. Hope this helps!
While a preferred solution requires zero lines of code, if you must trigger a redraw, do so in setNeedsDisplay
, which in turn invokes drawRect
.
No need to listen to notifications nor refactor the code.
Swift
override func layoutSubviews() {
super.layoutSubviews()
self.setNeedsDisplay()
}
Objective-C
- (void)layoutSubviews {
[super layoutSubviews];
[self setNeedsDisplay];
}
Note:layoutSubviews
is a UIView
method, not a UIViewController
method.
To make your chart rendered correctly when device orientation changes you need to update chart's layout, here is the code that you should add to your view controller:
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
_chartView.frame = self.view.bounds;
[_chartView strokeChart];
}
Zero Lines of Code
Use .redraw
Programmatically invoking myView.contentMode = .redraw
when creating the custom view should suffice. It is a single flag in IB and, as such, the 0 lines of code prefered way. See Stack Overflow How to trigger drawRect on UIView subclass.