Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is it bad to re-use a CGRect for repositioning views?
    primarykey
    data
    text
    <p>I have a large number of views in my project where I do programmatic re-sizing and re-positioning of the subviews. I do this in <code>layoutSubviews</code>, using code like this:</p> <pre><code>CGRect rect = self.btnOne.frame; // change values for rect self.btnOne.frame = rect; // re-use same CGRect to reposition other views rect = self.btnTwo.frame; // change values self.btnTwo.frame = rect; // etc. ... </code></pre> <p>This type of code has always worked fine for me for a couple of years, now. I have recently added a bunch of code like this to a co-worker's project, and it's now starting to behave very strangely. For no reason I can figure out, the re-used <code>rect</code> object here now sometimes randomly changes its own values between when it's assigned the frame of a view and when it is re-assigned to the view's frame at the end of the block. The result is subviews that are in the incorrect position. It seems that the error usually takes the form of <code>rect.origin.x</code> somehow acquiring the value of <code>rect.origin.y</code> or vice versa.</p> <p>Even weirder, this problem only occurs on a real device; the exact same code running on the simulator does not have the problem.</p> <p>The fix is to use a uniquely-declared CGRect object for each subview, like so:</p> <pre><code>CGRect rect = self.btnOne.frame; // change values for rect self.btnOne.frame = rect; // declare new CGRect to reposition other views CGRect rect2 = self.btnTwo.frame; // change values self.btnTwo.frame = rect2; </code></pre> <p>When I make this change, everything goes back to working correctly. But <strong>I'm really interested in knowing why this happens, and especially knowing why it happens on a device but not on a simulator</strong>. It also seems to not happen until a co-worker makes changes to the view, although it's not clear to me how any change (not related to positioning of views) could do this.</p> <p>One other change is that the project the code was imported into is using ARC, whereas my original code was not.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload