在swift中的右侧栏按钮项中添加徽章警报

时间:2018-05-14 12:00:04

标签: ios swift

我在右边的按钮位置放了一个简单的按钮。这个按钮显示我的购物车。现在我正在尝试在该按钮上放置一个徽章,以显示我的购物车项目数量。我正在尝试使用FontAwesome pods。我已经放置了一个正确的条形按钮项目,但是当我运行时它用购物车按钮替换了计数的右侧条形按钮。我希望它出现在购物车按钮上并显示计数。我怎么能得到它? 这就是我想在右蝙蝠按钮上放置徽章

let rightButton = UIButton(frame: CGRect(x:0,y:0,width:20,height:20))
  rightButton.titleLabel?.font = UIFont.fontAwesome(ofSize: 15)
  rightButton.setTitle(String.fontAwesomeIcon(name: .circle), for: .normal)

  let rightButtonItem : UIBarButtonItem = UIBarButtonItem(customView: rightButton)

  rightButton.titleLabel?.font = UIFont.fontAwesome(ofSize: 20)
  rightButton.titleLabel?.text = String.fontAwesomeIcon(name: .github)

  self.navigationItem.rightBarButtonItem = rightButtonItem

这是我的购物车按钮之前显示的方式 enter image description here

这是它正确的右键按钮代码 enter image description here

3 个答案:

答案 0 :(得分:5)

创建名为'UIBarButtonItem + Badge.swift'的文件 并添加以下代码

import UIKit

extension CAShapeLayer {
func drawRoundedRect(rect: CGRect, andColor color: UIColor, filled: Bool) {
    fillColor = filled ? color.cgColor : UIColor.white.cgColor
    strokeColor = color.cgColor
    path = UIBezierPath(roundedRect: rect, cornerRadius: 7).cgPath
}
}

private var handle: UInt8 = 0;

extension UIBarButtonItem {
private var badgeLayer: CAShapeLayer? {
    if let b: AnyObject = objc_getAssociatedObject(self, &handle) as AnyObject? {
        return b as? CAShapeLayer
    } else {
        return nil
    }
}

func setBadge(text: String?, withOffsetFromTopRight offset: CGPoint = CGPoint.zero, andColor color:UIColor = UIColor.red, andFilled filled: Bool = true, andFontSize fontSize: CGFloat = 11)
{
    badgeLayer?.removeFromSuperlayer()

    if (text == nil || text == "") {
        return
    }

    addBadge(text: text!, withOffset: offset, andColor: color, andFilled: filled)
}

private func addBadge(text: String, withOffset offset: CGPoint = CGPoint.zero, andColor color: UIColor = UIColor.red, andFilled filled: Bool = true, andFontSize fontSize: CGFloat = 11)
{
    guard let view = self.value(forKey: "view") as? UIView else { return }

    var font = UIFont.systemFont(ofSize: fontSize)

     if #available(iOS 9.0, *) { font = UIFont.monospacedDigitSystemFont(ofSize: fontSize, weight: UIFont.Weight.regular) } 
     let badgeSize = text.size(withAttributes: [NSAttributedStringKey.font: font])

    // Initialize Badge
    let badge = CAShapeLayer()

    let height = badgeSize.height;
    var width = badgeSize.width + 2 /* padding */

    //make sure we have at least a circle
    if (width < height) {
        width = height
    }

    //x position is offset from right-hand side
    let x = view.frame.width - width + offset.x

    let badgeFrame = CGRect(origin: CGPoint(x: x, y: offset.y), size: CGSize(width: width, height: height))

    badge.drawRoundedRect(rect: badgeFrame, andColor: color, filled: filled)
    view.layer.addSublayer(badge)

    // Initialiaze Badge's label
    let label = CATextLayer()
    label.string = text
    label.alignmentMode = kCAAlignmentCenter
    label.font = font
    label.fontSize = font.pointSize

    label.frame = badgeFrame
    label.foregroundColor = filled ? UIColor.white.cgColor : color.cgColor
    label.backgroundColor = UIColor.clear.cgColor
    label.contentsScale = UIScreen.main.scale
    badge.addSublayer(label)

    // Save Badge as UIBarButtonItem property
    objc_setAssociatedObject(self, &handle, badge, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}

private func removeBadge() {
    badgeLayer?.removeFromSuperlayer()
}
}

现在简单地在UIBarButtonItem中添加徽章,如下所示:

let rightBarButton = self.navigationItem.rightBarButtonItem

rightBarButton?.addBadge(number: 4)

答案 1 :(得分:0)

这是简单的解决方案

let filterBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30))
filterBtn.setImage(UIImage.fontAwesomeIcon(name: .filter, style: .solid,
                                                   textColor: UIColor.white,
                                                   size: CGSize(width: 25, height: 25)), for: .normal)
filterBtn.addTarget(self, action: #selector(filterTapped), for: .touchUpInside)

let lblBadge = UILabel.init(frame: CGRect.init(x: 20, y: 0, width: 15, height: 15))
self.lblBadge.backgroundColor = COLOR_GREEN
self.lblBadge.clipsToBounds = true
self.lblBadge.layer.cornerRadius = 7
self.lblBadge.textColor = UIColor.white
self.lblBadge.font = FontLatoRegular(s: 10)
self.lblBadge.textAlignment = .center

filterBtn.addSubview(self.lblBadge)

self.navigationItem.rightBarButtonItems = [UIBarButtonItem.init(customView: filterBtn)]

答案 2 :(得分:-2)

extension UIButton {

  func withBadge(number: Int) {

        let badge = PaddingLabel()
        badge.leftInset = 4
        badge.rightInset = 4
        badge.backgroundColor = .red
        badge.layer.cornerRadius = 7
        badge.layer.masksToBounds = true
        badge.text = "\(number)"
        badge.textColor = .white
        badge.textAlignment = .center
        badge.font = .systemFont(ofSize: 12)

        if number > 0 {

            self.addSubview(badge)
            self.addConstraintsWithFormat("H:[v0]|", views: badge)
            self.addConstraintsWithFormat("V:|[v0]", views: badge)

        } else {
            for each in self.subviews {
                if each is PaddingLabel {
                    each.removeFromSuperview()
                }
            }
        }
}


@IBDesignable class PaddingLabel: UILabel {

    @IBInspectable var topInset: CGFloat = 0.0
    @IBInspectable var bottomInset: CGFloat = 0.0
    @IBInspectable var leftInset: CGFloat = 8.0
    @IBInspectable var rightInset: CGFloat = 8.0

    override func drawText(in rect: CGRect) {
        let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
        super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }

    override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        return CGSize(width: size.width + leftInset + rightInset,
                      height: size.height + topInset + bottomInset)
    }
}