Xamarin.iOS – Create UILabel with C#

In this lesson

  • Xamarin Studio Intellisense
  • Specify Location and Size with CGRect
  • Add UILabel to UIViewController’s View
01:23 C# 100


Tap on time to skip ahead


Alright, so let’s add a UI element. We’re going to create a UILabel. I’m going to say var helloLabel = new UILabel(). And again, as we’re typing, Xamarin Studio has this really nice Intellisense that let’s us take shortcuts and let us know what’s available. I can say new UILabel. You’ll see Xamarin Studio tells us what the constructor of our object expects.


Right now, if I hit the down key, I can see a couple things. By default, you want to specify what’s know as a frame. Basically, a frame is an object that specifies the XY position of the object as well as the width and height. If I scroll down, I can just make one without anything in the constructor. Or, the third option is this NSCoder parameter, which we can probably explore much later because I never used it.


I’m going to go ahead and specify bounds and position of our label by creating a new CGRect, like so. Now, when I do this, again, it’s red. If I hit option return, I specify I’m using CoreGraphics. CoreGraphics is a library that comes with iOS development in general and Xcode. In the constructor of my CGRect, again, if I press up and down, I can look through the different parameters that this object takes in this constructor. As you can see here that I can specify the XY position as well as the width and height. I’m going to give it an X position of 10, let’s say 100 for Y, let’s give it 200 width and then let’s say 50 height. I instantiated the label but I actually haven’t added it to the view.


All UViewControllers have a reference to View. Now, some developers absolutely hate the word ‘this.’ I use it to just to be explicit sometimes. Especially in cases like this when I’m trying to explain things. I’m going to say, “this.View.AddSubview.” Again, the Xamarin Studio has given us nice Intellisense to let us know all of the potential things that we can add or invoke and use. I use Intellisense a lot more than I do API documents, just so I can figure out what’s actually available to me. I say, “AddSubview,” I can then say, “Add our hello label” like such. Now it should show up. There it is!