【问题标题】:Adding badge to chat button when got message收到消息时将徽章添加到聊天按钮
【发布时间】:2018-12-11 10:17:31
【问题描述】:

我有社交网络应用程序。应用程序图标徽章和 tabbar.item 徽章工作正常。但我在主页上有一个消息按钮,就像 instagram 一样。我希望此按钮在收到新消息时显示徽章。这是我的收件箱推送通知功能

// Send Push notification
        let pushStr = "\(PFUser.current()![USER_USERNAME]!) sent you a message.:\nRelated post: \(self.adObj[ADS_TITLE]!)"
        //\(self.lastMessageStr)

        let data = [ "badge" : "Increment",
                     "alert" : pushStr,
                     "sound" : "bingbong.aiff"
        ]
        let request = [
                    "someKey" : self.userObj.objectId!,
                    "data" : data
        ] as [String : Any]
        PFCloud.callFunction(inBackground: "push", withParameters: request as [String : Any], block: { (results, error) in
            if error == nil {
                print ("\nPUSH SENT TO: \(self.userObj[USER_USERNAME]!)\nMESSAGE: \(pushStr)\n")
            } else {
                print ("\(error!.localizedDescription)")
            }
        })

这是我在主页视图控制器中的聊天按钮

    @IBAction func chatsButt(_ sender: Any) {
    if PFUser.current() != nil { 
        let aVC = storyboard?.instantiateViewController(withIdentifier: "Chats") as! Chats
        navigationController?.pushViewController(aVC, animated: true)
    } else {
        showLoginAlert("You need to be logged in to see your Chats. Want to Login now?")
    }
}

收到新消息时,只有消息按钮应该显示徽章, 但是当得到新的喜欢时,只有标签栏项目应该显示徽章。我该怎么做?

【问题讨论】:

    标签: swift push-notification uibutton message badge


    【解决方案1】:

    我有这个助手:

    //
    //  UIButton+BadgeCircle.swift
    //
    //  Created by João Marcelo Ferreira Pinho on 27/08/18.
    //  Copyright © 2018 WIT Software. All rights reserved.
    //
    // source: https://gist.github.com/freedom27/c709923b163e26405f62b799437243f4
    
    import UIKit
    
    fileprivate struct Badge {
        static let size: CGSize = CGSize(width: 16, height: 16)
        static let offSet: CGFloat = 8
        static let fontSize: CGFloat = 11.0
        static let color: UIColor = .black
        static let filled: Bool = true
    }
    
    private var handle: UInt8 = 0
    
    extension UIButton {
    
        private var badgeLayer: CAShapeLayer? {
            if let badge: AnyObject = objc_getAssociatedObject(self, &handle) as AnyObject? {
                return badge as? CAShapeLayer
            } else {
                return nil
            }
        }
    
        func addBadge(number: Int, withColor color: UIColor = Badge.color, filled: Bool = Badge.filled) {
            badgeLayer?.removeFromSuperlayer()
    
            let badge = CAShapeLayer()
            let location = CGPoint(x: frame.width - Badge.offSet, y: -Badge.offSet)
            badge.drawCircleAt(location, withColor: color, filled: filled)
            layer.addSublayer(badge)
    
            let label = CATextLayer()
            label.string = "\(number)"
            label.alignmentMode = kCAAlignmentCenter
            label.fontSize = Badge.fontSize
            label.frame = CGRect(origin: CGPoint(x: location.x, y: -6.5), size: Badge.size)
            label.foregroundColor = filled ? UIColor.white.cgColor : color.cgColor
            label.backgroundColor = UIColor.clear.cgColor
            label.contentsScale = UIScreen.main.scale
            badge.addSublayer(label)
    
            // Save Badge as UIButton property
            objc_setAssociatedObject(self, &handle, badge, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    
        func removeBadge() {
            badgeLayer?.removeFromSuperlayer()
        }
    }
    
    private extension CAShapeLayer {
    
        func drawCircleAt(_ location: CGPoint, withColor color: UIColor, filled: Bool) {
            fillColor = filled ? color.cgColor : UIColor.white.cgColor
            strokeColor = color.cgColor
            path = UIBezierPath(ovalIn: CGRect(origin: location, size: Badge.size)).cgPath
        }
    }
    

    将此代码粘贴到一个swift文件中,然后您可以简单地调用button.addBadge(number: 2)并绘制一个自定义徽章。

    您可以使用 fileprivate struct Badge 自定义您的徽章,这些是我的项目主题的默认值,您的可以不同。

    在 cmets 类中,您可以找到我的代码所基于的位置(来源:https://gist.github.com/freedom27/c709923b163e26405f62b799437243f4)。

    【讨论】:

    • 感谢Pincha的帮助,其实我想要的是;收到新消息时,只有消息按钮显示徽章,但收到新消息时,只有标签栏项目显示徽章。我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多