Xamarin.iOS – Create UIButton with C#

In this lesson

  • Set Location and Size of UIButton via CGRect
  • Set Title of UIButton for different UIControl States
  • Set background color of UIButton


Tap on time to skip ahead


Let’s go ahead and make a button. I’m going to say var testButton = new UIButton. In this case, if we look through the constructor arguments, I can specify just the frame I wanted too or the type. I’m just going to specify the UIButton type for now. I’m going to select custom. Then, in the next line, I’m going to say the frame = new CGRect, let’s say ten, let’s say 175, then width 100, 50.


If I go to set the text of it, you’ll see there is no text property. What you have to do instead is say SetTitle. We have two arguments here. The actual title, “say goodbye.” Then we have to specify the UIControlState. I’m going to say normal and we’ll play with this in a minute to better understand what it does. I’m going to say this.View.AddSubView (testButton). Now, if I run it, we should see our button. Why don’t we?


Test button, Title Color = UIColor.Red. So that’s only a getter. I have to say SetTitleColor, UIColor.Red. UIControlState.Normal. There we go!


Also, if we notice, we see these ellipses, it means we need to make our button a bit wider. TestButton.BackgroundColor = UIColor.Gray. What I could do is I could say, var screenWidth = View.Frame.Width. Basically, we’re saying what’s our view’s width? I could say for our width here, I could say screenWidth * .8, like so.


Going back to the UIControlStates. I can say the set title color is red when the button is in normal state. If I say highlighted, I think that might be the one I want, might help if I change the color for that state. So if I said green, when I press down it goes green, like that.