gpt4 book ai didi

Swift 将徽章添加到导航 barButtonItem 和 UIButton

转载 作者:IT王子 更新时间:2023-10-29 05:20:57 26 4
gpt4 key购买 nike

我正在尝试在我的通知按钮上显示徽章,在应用程序中显示在 AppIcon 上。

到目前为止,我所研究的一切都与 Obj 有关。 C,但没有具体讨论将该解决方案实现到 Swift 中的方法,

请帮助找到解决方案,添加自定义类/代码以在 UiBarbutton 和 UiButton 上实现 Badge。

目前研究:

https://github.com/Marxon13/M13BadgeView

连同 MKBadge 类等

最佳答案

有一个更优雅的解决方案,带有 UIButtonItem 的扩展

extension CAShapeLayer {
func drawCircleAtLocation(location: CGPoint, withRadius radius: CGFloat, andColor color: UIColor, filled: Bool) {
fillColor = filled ? color.cgColor : UIColor.white.cgColor
strokeColor = color.cgColor
let origin = CGPoint(x: location.x - radius, y: location.y - radius)
path = UIBezierPath(ovalIn: CGRect(origin: origin, size: CGSize(width: radius * 2, height: radius * 2))).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 addBadge(number: Int, withOffset offset: CGPoint = CGPoint.zero, andColor color: UIColor = UIColor.red, andFilled filled: Bool = true) {
guard let view = self.value(forKey: "view") as? UIView else { return }

badgeLayer?.removeFromSuperlayer()

// Initialize Badge
let badge = CAShapeLayer()
let radius = CGFloat(7)
let location = CGPoint(x: view.frame.width - (radius + offset.x), y: (radius + offset.y))
badge.drawCircleAtLocation(location: location, withRadius: radius, andColor: color, filled: filled)
view.layer.addSublayer(badge)

// Initialiaze Badge's label
let label = CATextLayer()
label.string = "\(number)"
label.alignmentMode = CATextLayerAlignmentMode.center
label.fontSize = 11
label.frame = CGRect(origin: CGPoint(x: location.x - 4, y: offset.y), size: CGSize(width: 8, height: 16))
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)
}

func updateBadge(number: Int) {
if let text = badgeLayer?.sublayers?.filter({ $0 is CATextLayer }).first as? CATextLayer {
text.string = "\(number)"
}
}

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

这个很棒的代码是由 Stefano Vettor 创建的,您可以在以下位置找到所有详细信息: https://gist.github.com/freedom27/c709923b163e26405f62b799437243f4

关于Swift 将徽章添加到导航 barButtonItem 和 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31236210/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com