Search code examples
iosperformanceuiviewframecgrect

calling setFrame multiple times?


i am calling setFrames multiple times for the same view.

for example after setting ltr views frames, i check if the layout should be rtl and change the views frames again.

-(void)setViewsFrames:(BOOL)RTL{
      view1.frame = CGRECMAKE();
      view2.frame = CGRECMAKE();
      view3.frame = CGRECMAKE();
         .
         .
         .
      if(RTL){
         [view1 setRtlFrame];
         [view2 setRtlFrame];
         [view3 setRtlFrame];
            .
            .
            .


      }

}


-(void)setRtlFrame{
    CGRect RTLFrame = self.frame;
    RTLFrame.origin.x = [self superview].frame.size.width - self.frame.origin.x - self.frame.size.width;
    [self setFrame:RTLFrame];
}

does calling setFrames multiple time force the system to draw the view multiple times ? and may that effect performance.

I am using that also in UICollectionViewCell, so the system calls setViewsFrames: every time she want to draw the cell.

EDIT: i've did a small test. i check when drawRect is called and here is the result:

  • it's called just one time, no matter how much times setFrame was called.

  • in UICollectionCellView it called just when the cell created or at reload.


Solution

  • setting the frame calls 'setNeedsLayout' and then on the next runloop iteration, IOS knows to layout & redraw the view.

    there'd be no point in layouting / redrawing stuff the user doesn't see so iOS coalesces the calls for you -- if you let it by using the setNeedsXY methods

    so the overhead of setting the frame is normally minimal

    (except if you deal with custom (badly implemented) views [which you don't ;)])