Search code examples
iosswiftvariablesswift4cgrect

Set a variable equal to a view's frame without the value changing when view's frame changes


I would like to know the original value of a frame before it is changed. To do this I thought of this:

var baseViewOriginalFrame: CGRect!

func changeFrame() {
   baseViewOriginalFrame = boxView.frame
   boxView.transform = CGAffineTransform.identity.translatedBy(x: 0, y: +5)
}

I noticed that the original frame was in fact the current frame of the boxView, so I read Setting a variable equal to another variable, and learned that the originalFrame variable just stores a location of the object.

So how can I achieve this (saving the original frame of the boxView)?


Solution

  • This comes down to the difference between reference types and value types.

    In Swift, when you have a variable that is a value type (link Ints, Strings, etc), then the variable holds that value. When you have a variable that is a reference type (e.g. a Class), then it holds a reference to that object in memory.

    This means that when you pass a value type variable around, you're passing around the actual data that the variable holds. But when you pass around a reference type variable, you're passing around a reference to that object.

    Take the following code snippet, you can see that when you make a copy of a value type, you get an actual copy of it. When you make a copy of a reference type, you just get another reference to the same object in memory, which means any changes are reflected in the other variable, because they all reference the same object.

    // Structs are a VALUE type
    struct myStruct {
        var value: Int
    
        init(x: Int) {
            self.value = x
        }
    }
    
    // Classes are a REFERENCE type
    class myClass {
        var value: Int
    
        init(x: Int) {
            self.value = x
        }
    }
    
    var a = myStruct(x: 5)
    var originalA = a       // This has made a copy of a, and stores it in originalA
    a.value = 100
    
    print(originalA.value)
    print(a.value)
    
    var b = myClass(x: 5)
    var originalB = b       // This is still referencing the same object as the variable b.
    b.value = 100
    
    print(originalB.value)
    print(b.value)
    

    Now as for your specific example, I am confused as to why it doesn't work, because from what I can see CGRect is a struct, which is a value type, so making a copy the way you have should work fine. In fact, I just added the code you have to the end of a method in one of my apps, and it worked exactly as you would expect:

    let x = textView.frame
    textView.transform = CGAffineTransform.identity.translatedBy(x: 0, y: +5)
    print(x)   // Prints (16.0, *83.0*, 343.0, 564.0)
    print(textView.frame) // Prints (16.0, *88.0*, 343.0, 564.0)
    

    Hope this helps, Jacob.