Wednesday, November 21, 2012

Creating a custom image on UIToolbar in MonoTouch


Recently I had to create a custom button for UIToolbar. Specifically, in my case, it was not a button, but a separator. I was very surprised to find out that UIBarButtonItem does not have a height attribute. Turns out there is a workaround to set a customer hight for a UIBarButtonItem. This is what I did:


// Create a custom image of needed hight with a regular button
var customerImageButton = new UIButton (UIButtonType.Custom);
customerImageButton.SetBackgroundImage (UIImage.FromFile 
                   ("Images/separator.png"), UIControlState.Normal);
   
customerImageButton.Frame = new RectangleF (0, 0, 3, 46);

// Initialize new UIBarButtonItem from a custom view - new button
var customerBarButton = new UIBarButtonItem (customerImageButton);

// Make updates to the existing bar
var barButtonList = new List ();

// Update toolbar in xib/story board with custom items
for (var i =0; i< tlbrMainToolbar.Items.Length; i++)  
{  
  if (i == 4)    
  {
      // replace placeholder button with a custom separator
      // In my case it was button 4 
      barButtonList.Add(customerBarButton);   
  }    
  else   
  {   
      barButtonList.Add (tlbrMainToolbar.Items[i]);   
  } 
}

// Set the new button list for the toolbar 
tlbrMainToolbar.Items = barButtonList.ToArray();

Hope this saves someone time!

0 comments:

Post a Comment