Xamarin.iOS – Resizing UIViews with DidRotate

In this lesson

  • Use ViewDidRotate to detect device orientation changes
  • Resize UILabel via CGRect
  • Output debug info with System.Diagnostics 


Tap on time to skip ahead


As we can see, our UI elements as we flip between the different orientations, aren’t really resizing. There are some things that we could potentially do to counteract this. For example, I can say, override DidRotate. I can say, let’s see something. Let’s see how size gets reported. I’m going to say Debug.WriteLine and now I’m going to say View Width like so and I’m going to say View.Frame.Width.


Another trick we can do is, Xamarin Studio has these really nice refactoring tools. I’m going to specify using string.Format. What this now does is I have this curly bracket zero, and that’s where my View.Frame.Width is going to get inserted.


If we go back to what we’ve got going on with the simulator and the application output here, we can see that as … we rotate the view width is being reported to be different amounts. One of the things we could do in theory-I’ve done this in the past, I can actually change our view label frame. Just saying View.Frame.Width, TestLabel.Frame.Width will not work. As you can see, you cannot modify a value type, a return type, blah blah blah.


What we’re going to do instead, we have to override the whole frame object through text label. We’re going to say new CGRect. We’re going to say TestLabel.Frame.Location because one of the constructors for CGRect can take just a location object and a size object. I’m going to say new CGSize, we’re going to say View.Frame.Width. Then we’re going to say what the TestLabel.Frame.Height is. Just to clarify a little bit, it’s the view’s frame, which is basically your whole screen.


Now, in theory, when we run this, when I rotate it, it’s now bigger and smaller. Now that I’m running off the screen a little but, what I can do is, let’s go ahead and subtract a little bit here. We can make sure it is working the way we intended. Now, if I rotate, you can see it’s resizing accordingly.