Archives

  • Categories

  • Programatically Creating a UIButton with MonoTouch

    This is probably a really basic post but as I am a still learning the MonoTouch Framework and I couldn’t find anywhere on the Internet explaining how to do it. Anyway today I was trying to programmatically create a UIButton in MonoTouch and set the button type.

     

    There is a ButtonType property on the instantiated UIButton object but its read only and I couldn’t see any constructor that took a buttontype.

     

    In the end the answer was quite simple there is a static factory method on the UIButton class that you use to instantiate a new button. The code looks something like this.

     

       1: var button = UIButton.FromType(UIButtonType.RoundedRect);

       2: button.frame = new RectangleF(100f, 100f, 100f, 100f);

       3: button.SetTitle("click me", UIControlState.Normal);

     

    Technorati Tags:

    Tags: , , ,

    6 Responses to “Programatically Creating a UIButton with MonoTouch”


    1. Sichy says:

      Nice one, however maybe no sample existed as it is a simple conversion from Objective C. That is the excellent stuff of Monotouch, that it is 1 to 1 mapping to Cocoa Touch API.

    2. I was looking for this the other day as well.
      Thanks!

    3. Stuart C says:

      I agree the solution is very simple it is a simple conversion and I was being dumb :)

    4. Jav says:

      Nice one, just what I was after.

    5. Levitikon says:

      I tried this with an extended button and there’s a problem with the FromType part. How would you recommend doing this with a scenario like this:

      public class MyButton : UIButton
      {

      }

      var button = MyButton.FromType(UIButtonType.RoundedRect);

    Leave a Reply