iOS Custom badge control

By June 4, 2014Blog

Ever needed to create custom badge to UITabBarItem? Well here you go. I think it is pretty selfexplanatory.

public static class UITabBarItem_CustomBadge
	{
		public static void SetCustomBadgeValue (this UITabBarItem tabBarItem, string value, UIFont font, UIColor textColor, UIColor borderColor)
		{
			UIView view = (UIView)tabBarItem.ValueForKey (new NSString ("view"));

			tabBarItem.BadgeValue = value;

			// remove old one
			foreach (UIView subview in view.Subviews)
			{
				if (subview.Tag == 99) // badge has tag of 99
				{
					subview.RemoveFromSuperview ();

					break;
				}
			}

			foreach (UIView subview in view.Subviews)
			{
				if (subview.ToString ().StartsWith ("<_UIBadgeView:"))
				{
					// create new label view that we can style.
					// remove background, add border, make it nice
					var label = new UILabel (subview.Frame);

					label.TextAlignment = UITextAlignment.Center;
					label.Font = font;
					label.Text = value;
					label.BackgroundColor = borderColor.ColorWithAlpha (.5f);
					label.TextColor = textColor;
					label.Layer.BorderColor = borderColor.CGColor;
					label.Layer.BorderWidth = 1;
					label.Layer.CornerRadius = label.Frame.Height / 2;
					label.Layer.MasksToBounds = true;

					view.AddSubview (label);
					subview.Hidden = true;

					label.Tag = 99; // fake it here for iOS 😉
				}
			}
		}
	}

Enjoy and happy coding!