使用MIBadgeButton-Swift为UIButtonitem添加徽章

时间:2015-12-15 12:14:33

标签: ios swift uinavigationcontroller uibarbuttonitem

我试图为我的UIBarButtonItem添加徽章,为此我找到了一个github:

MIBadgeButton-Swift

但我不知道如何使用它。

这是我的自定义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;

我如何使用MIBadgeButton-Swift为我的UIBarButtonItem制作徽章?

2 个答案:

答案 0 :(得分:5)

以下是自定义视图和故事板

的两个示例

通过设置自定义类来自故事板:

enter image description here

CODE

@IBOutlet var btnRightBadge: MIBadgeButton!

override func viewDidLoad() {
    super.viewDidLoad()

    //Custom
    let badgeButton : MIBadgeButton = MIBadgeButton(frame: CGRectMake(0, 0, 40, 40))
    badgeButton.setTitle("T1", forState: UIControlState.Normal)
    badgeButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
    badgeButton.badgeString = "1";
    let barButton : UIBarButtonItem = UIBarButtonItem(customView: badgeButton)
    self.navigationItem.leftBarButtonItem = barButton

    //From Storyboard
    btnRightBadge.badgeString = "5"
}

输出

enter image description here

您也可以使用ENMBadgedBarButtonItem-Swift

答案 1 :(得分:2)

尝试一次。

//Property
    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