sali sali - 1 year ago 284
Swift Question

Add a badge to UIButtonitem with MIBadgeButton-Swift

I'm trying to add a badge to my UIBarButtonItem and for that I have found a this github :


but I don't know how to use it.

This is my code which makes my custom UIBarButtonItem:

let shopingCartBTN = UIButton(type: UIButtonType.Custom)
shopingCartBTN.setImage(UIImage(named: "shopingCarBarIcon"), forState: UIControlState.Normal)
shopingCartBTN.imageView?.image = UIImage(named: "shopingCarBarIcon")
shopingCartBTN.frame = CGRectMake(0, 0, 60, 30)//Just increase the width of button
shopingCartBTN.setTitle("5", forState: .Normal)
shopingCartBTN.addTarget(self, action: "", forControlEvents: UIControlEvents.TouchUpInside)
let customBarItem = UIBarButtonItem(customView: shopingCartBTN)
self.navigationItem.leftBarButtonItem = customBarItem;

How could I use the MIBadgeButton-Swift to make a badge for my UIBarButtonItem?

Answer Source

Try this once.

    var cartBarbuttonItem:MIBadgeButton?

self.cartBarbuttonItem = MIBadgeButton(frame: CGRectMake(40, 5, 40, 44))
self.cartBarbuttonItem?.initWithFrame(frame: CGRectMake(40, 5, 40, 44), withBadgeString: "0", withBadgeInsets:  UIEdgeInsetsMake(15, 2, 0, 15))
self.cartBarbuttonItem?.setImage(UIImage(named: "test"), forState: .Normal)
self.cartBarbuttonItem?.setImage(UIImage(named: "test"), forState: .Selected)
self.cartBarbuttonItem?.addTarget(self, action: Selector("loadCart"), forControlEvents: UIControlEvents.TouchUpInside)

self.navigationItem.setLeftBarButtonItem = self.cartBarbuttonItem
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download