kitasuke / PagingMenuController

Paging view controller with customizable menu in Swift
MIT License
2.5k stars 449 forks source link

Add badge to the segmented control item #264

Open tunidev opened 8 years ago

tunidev commented 8 years ago

how to add a badge next to menu items

badge

kitasuke commented 8 years ago

Badge option is not supported yet. You can use custom view instead. https://github.com/kitasuke/PagingMenuController/blob/master/Pod/Classes/Protocols/MenuItemViewCustomizable.swift#L30

spsammy commented 7 years ago

Is there any example of using a custom view? I'd like to add a badge also.

kitasuke commented 7 years ago

Something like this.

struct MenuItemRepository: MenuItemViewCustomizable {
    var displayMode: MenuItemDisplayMode {
        return .custom(view: yourBadgeView)
    }
}
morteg commented 7 years ago

@spsammy

I use pod "MIBadgeButton_Swift" to display badge button on menu item. Here is my implementation :

struct MenuItemCheckout: MenuItemViewCustomizable {
    var displayMode: MenuItemDisplayMode {
        let buttonView = MenuBadgeView(frame: CGRect(x: 0, y: 0, width: 125, height: 50))
        return .custom(view: buttonView)
    }
}
class MenuBadgeView: UIView {
    let cartBadgeButton: MIBadgeButton = {
        var image = UIImage(named: "checkout")?.withRenderingMode(.alwaysTemplate)
        let button = MIBadgeButton()
        button.setImage(image, for: .normal)
        button.isUserInteractionEnabled = false
        button.tintColor = UIColor.deselectedMenuItem //intital button tint grey
        return button
    }()

    override init(frame: CGRect){
        super.init(frame: frame)
        setupViews()

        NotificationCenter.default.addObserver(forName: .arrayValueChanged, object: nil, queue: OperationQueue.main) { [weak self] (notif) in
            self?.cartBadgeButton.badgeString = ProductCart.sharedInstance.badge
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupViews() {

        addSubview(cartBadgeButton)

        addConstraintsWithFormat("H:[v0(28)]", views: cartBadgeButton)
        addConstraintsWithFormat("V:[v0(28)]", views: cartBadgeButton)

        addConstraint(NSLayoutConstraint(item: cartBadgeButton, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier:1, constant: 0)) //center menu icons
        addConstraint(NSLayoutConstraint(item: cartBadgeButton, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier:1, constant: 0))
        cartBadgeButton.badgeString = ProductCart.sharedInstance.badge

    }

    override func layoutSubviews() {
        super.layoutSubviews()
        cartBadgeButton.badgeEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 0)
    }
}