最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

[已解决]swift带badge的UIBarButtonItem

iOS crifan 1487浏览 0评论

之前打算是自己手动去画的。

但是,如果这样:

        let messageBarItem:UIBarButtonItem = UIBarButtonItem(image: NaviMessageImage, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.showMessageVC))

则只能是手动的额外去:

//draw a badge view

func drawBadgeView(badgeString:String, badgeRadius:CGFloat = 8.5, circleFillColor:UIColor = UIColor.redColor()) -> UIView {

    let badgeFrame = CGRectMake(0, 0, badgeRadius * 2, badgeRadius * 2)

    let circleLayer = drawCircleLayer(badgeRadius, fillColor: circleFillColor)

    //let badgeView = UIView(frame: CGRectMake(0, 0, badgeRadius*2, badgeRadius*2))

    let badgeView = UIView(frame: badgeFrame)

    badgeView.layer.addSublayer(circleLayer)

    //let badgeLabel:UILabel = UILabel(frame: CGRectMake(0, 0, badgeRadius*2, badgeRadius*2))

    let badgeLabel:UILabel = UILabel(frame: badgeFrame)

    badgeLabel.text = badgeString

    badgeLabel.backgroundColor = UIColor.clearColor()

    badgeLabel.textAlignment = NSTextAlignment.Center

    badgeLabel.font = UIFont.systemFontOfSize(11)

    badgeLabel.textColor = UIColor.whiteColor()

    badgeView.addSubview(badgeLabel)

    badgeView.bringSubviewToFront(badgeLabel)

    return badgeView

}

    func updateMessageBadge(badgeNum:Int) {

        if let rightBarItem = SingletonMainVC().navigationItem.rightBarButtonItem {

            if badgeNum >= 0 {

                let badgeView = drawBadgeView(String(badgeNum))

                let messageImageView = UIImageView(image: NaviMessageImage)

                badgeView.frame.origin.x = messageImageView.frame.size.width

                    – badgeView.frame.width + 4

                badgeView.frame.origin.y -= 4

                messageImageView.addSubview(badgeView)

            } else {

                rightBarItem.image = NaviMessageImage

            }

        }

    }

把badge当做view,合并到对应的image上面-》可能导致barite的image的大小变化-》导致是否加了badge,图片位置都变化了-》很难看-》也很难实现,难画

后来看到:

swift image with badge

swift – How to Add a badge to my ImageView in ios? – Stack Overflow

iphone – How can I add a badge to a standard UIButton? – Stack Overflow

-》ckteebe/CustomBadge: CustomBadge is an Objective-C based component to create customized Badges for any given View.

但是不是我要的

Search results for badge – Cocoa Controls

-》BBBadgeBarButtonItem for iOS – Cocoa Controls

-》TanguyAladenise/BBBadgeBarButtonItem: A BarButtonItem with a badge on top.

看起来不错,虽然是oc的但是swift也可以调用。

(好像是同一个:mikeMTOL/UIBarButtonItem-Badge: UIBarButtonItem+Badge

不支持carthage,所以报错:

licrifandeMacBook-Pro:SalesAppiOS crifan$ carthage update –platform iOS BBBadgeBarButtonItem

*** Cloning BBBadgeBarButtonItem

*** Fetching SwiftyJSON

*** Fetching TextFieldEffects

*** Fetching MGSwipeTableCell

*** Fetching SwiftHEXColors

*** Fetching Charts

*** Fetching SwiftKeychainWrapper

*** Fetching Alamofire

*** Fetching XCGLogger

*** Fetching realm-cocoa

*** Fetching Cartography

*** Checking out BBBadgeBarButtonItem at “1.2”

*** xcodebuild output can be found in /var/folders/46/2hjxz38n22n3ypp_5f6_p__00000gn/T/carthage-xcodebuild.RKC9oW.log

*** Skipped building BBBadgeBarButtonItem due to the error:

Dependency “BBBadgeBarButtonItem” has no shared framework schemes for any of the platforms: iOS

If you believe this to be an error, please file an issue with the maintainers at https://github.com/TanguyAladenise/BBBadgeBarButtonItem/issues/new

导入代码:

再去添加到头文件中:

然后去使用:

        let messageBarItem:BBBadgeBarButtonItem = BBBadgeBarButtonItem(image: NaviMessageImage, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.showMessageVC))

        messageBarItem.badgeValue = “6”

        SingletonMainVC().navigationItem.setRightBarButtonItem(messageBarItem, animated: false)

结果没生效:

        let messageButton:UIButton = UIButton()

        messageButton.setImage(NaviMessageImage, forState: UIControlState.Normal)

        messageButton.addTarget(self, action: #selector(self.showMessageVC), forControlEvents: UIControlEvents.TouchUpInside)

        let messageBarItem:BBBadgeBarButtonItem = BBBadgeBarButtonItem(customUIButton: messageButton)

        messageBarItem.badgeValue = “6”

        SingletonMainVC().navigationItem.setRightBarButtonItem(messageBarItem, animated: false)

效果:

改为:

        let messageButton:UIButton = UIButton()

        messageButton.frame = CGRectMake(0, 0, NaviMessageImage.size.width, NaviMessageImage.size.height)

        messageButton.setImage(NaviMessageImage, forState: UIControlState.Normal)

        messageButton.addTarget(self, action: #selector(self.showMessageVC), forControlEvents: UIControlEvents.TouchUpInside)

        let messageBarItem:BBBadgeBarButtonItem = BBBadgeBarButtonItem(customUIButton: messageButton)

        messageBarItem.badgeValue = “6”

        SingletonMainVC().navigationItem.setRightBarButtonItem(messageBarItem, animated: false)

效果:

        let messageButton:UIButton = UIButton()

        messageButton.frame = CGRectMake(0, 0, NaviMessageImage.size.width, NaviMessageImage.size.height)

        messageButton.setImage(NaviMessageImage, forState: UIControlState.Normal)

        messageButton.addTarget(self, action: #selector(self.showMessageVC), forControlEvents: UIControlEvents.TouchUpInside)

        let messageBarItem:BBBadgeBarButtonItem = BBBadgeBarButtonItem(customUIButton: messageButton)

        messageBarItem.badgeValue = “6”

//        messageBarItem.badgePadding = 6

//        messageBarItem.badgeMinSize = 8

//        messageBarItem.badgeOriginX = 7

//        messageBarItem.badgeOriginY = -9

        messageBarItem.badgePadding = 2

        messageBarItem.badgeMinSize = 2

        messageBarItem.badgeOriginX = 12

        messageBarItem.badgeOriginY = -7

        messageBarItem.badgeFont = UIFont.systemFontOfSize(11)

        SingletonMainVC().navigationItem.setRightBarButtonItem(messageBarItem, animated: false)

调整了半天,才调整为需要的效果:

之后更新badge的值,即可通过:

messageBarItem.badgeValue = “4”

即可:

[总结]

BBBadgeBarButtonItem总的来说,还算凑合:

但是参数设置,很蛋疼:

不能直接设置badge圆圈的radius,而是内部通过自己的规则去根据一些参数,包括badgePadding和badgeMinSize去计算圆圈的半径的。。。

[后记]

也看到另外几个,算是凑合的:

mustafaibrahim989/MIBadgeButton-Swift: iOS custom badge button.

cemolcay/BubbleControl-Swift: a bubble control highly inspired from facebook chat heads. written in swift

gemr/Sheriff: Badgify anything.

JaviSoto/JSBadgeView: Customizable UIKit badge view like the one on applications in the iOS springboard.

mustafaibrahim989/MIBadgeButton: iOS custom badge button designed for iOS 6&7.

matteogobbi/UIView-MGBadgeView: Category which allows to show and customize a badge on every object which inherits from UIView like UIButton, UILabel, UIImage, etc..

[后记 2016-06-07]

后来想要调整BBBadgeBarButtonItem中badge的位置,结果又是费了很大功夫去调整对应的值,但是都难达到要的效果

然后加上之前自己实现了,对于已有button添加badge的效果

所以索性,放弃让人蛋疼的BBBadgeBarButtonItem,自己去画badge

经过调整和优化,使用如下代码:

import UIKit

import Cartography

import Charts //https://github.com/danielgindi/Charts

let BadgeButtonDefaultBadgeInt:Int = 0

let BadgeButtonDefaultBadgeRadius:CGFloat = 7.0

let BadgeButtonDefaultBadgeFillColor:UIColor = UIColor.redColor()

let BadgeButtonDefaultBadgeFont:UIFont = UIFont.systemFontOfSize(10)

let BadgeButtonDefaultBadgeMoveDown:CGFloat = 0

let BadgeButtonDefaultBadgeMoveRight:CGFloat = 0

class BadgeButton: UIButton {

    var badgeView:UIView

    var badgeInt:Int {

        didSet {

            gLog.info(“badgeInt=\(badgeInt)”)

            self.updateBadgeView()

        }

    }

    var badgeRadius:CGFloat {

        didSet {

            gLog.info(“badgeRadius=\(badgeRadius)”)

            self.updateBadgeView()

        }

    }

    var badgeFillColor:UIColor {

        didSet {

            gLog.info(“badgeFillColor=\(badgeFillColor)”)

            self.updateBadgeView()

        }

    }

    var badgeFont:UIFont {

        didSet {

            gLog.info(“badgeFont=\(badgeFont)”)

            self.updateBadgeView()

        }

    }

    var badgeMoveDown:CGFloat {

        didSet {

            gLog.info(“badgeMoveDown=\(badgeMoveDown)”)

            self.updateBadgeView()

        }

    }

    var badgeMoveRight:CGFloat {

        didSet {

            gLog.info(“badgeMoveRight=\(badgeMoveRight)”)

            self.updateBadgeView()

        }

    }

    override init(frame: CGRect) {

        self.badgeView = UIView()

        self.badgeInt = BadgeButtonDefaultBadgeInt

        self.badgeRadius = BadgeButtonDefaultBadgeRadius

        self.badgeFillColor = BadgeButtonDefaultBadgeFillColor

        self.badgeFont = BadgeButtonDefaultBadgeFont

        self.badgeMoveDown = BadgeButtonDefaultBadgeMoveDown

        self.badgeMoveRight = BadgeButtonDefaultBadgeMoveRight

        super.init(frame: frame)

        self.updateBadgeView()

    }

    //    convenience init(badgeInt:Int = 0, badgeRadius:CGFloat = 7.0, badgeFillColor:UIColor = UIColor.redColor(), badgeFont:UIFont = UIFont.systemFontOfSize(10), badgeMoveDown:CGFloat = 0, badgeMoveRight:CGFloat = 0) {

    //    convenience init(badgeInt:Int = BadgeButtonDefaultBadgeInt, badgeRadius:CGFloat = BadgeButtonDefaultBadgeRadius, badgeFillColor:UIColor = BadgeButtonDefaultBadgeFillColor, badgeFont:UIFont = BadgeButtonDefaultBadgeFont, badgeMoveDown:CGFloat = BadgeButtonDefaultBadgeMoveDown, badgeMoveRight:CGFloat = BadgeButtonDefaultBadgeMoveRight) {

    convenience init(badgeInt:Int, badgeRadius:CGFloat = BadgeButtonDefaultBadgeRadius, badgeFillColor:UIColor = BadgeButtonDefaultBadgeFillColor, badgeFont:UIFont = BadgeButtonDefaultBadgeFont, badgeMoveDown:CGFloat = BadgeButtonDefaultBadgeMoveDown, badgeMoveRight:CGFloat = BadgeButtonDefaultBadgeMoveRight) {

        gLog.info(“badgeInt=\(badgeInt), badgeRadius=\(badgeRadius), badgeFillColor=\(badgeFillColor), badgeFont=\(badgeFont), badgeMoveDown=\(badgeMoveDown), badgeMoveRight=\(badgeMoveRight)”)

        self.init(frame: CGRectZero)

        self.badgeView = UIView()

        self.badgeInt = badgeInt

        self.badgeRadius = badgeRadius

        self.badgeFillColor = badgeFillColor

        self.badgeFont = badgeFont

        self.badgeMoveDown = badgeMoveDown

        self.badgeMoveRight = badgeMoveRight

        //1. badge view

        self.updateBadgeView()

    }

    required init?(coder aDecoder: NSCoder) {

        fatalError(“init(coder:) has not been implemented”)

    }

    func updateBadgeView() {

        gLog.info(“badgeInt=\(badgeInt)”)

        self.badgeView.removeFromSuperview()

        if badgeInt > 0 {

            self.badgeView.hidden = false

            self.badgeView = drawBadgeView(String(badgeInt), badgeRadius: self.badgeRadius, circleFillColor: self.badgeFillColor, badgeFont: self.badgeFont)

            gLog.debug(“badgeView.frame=\(badgeView.frame)”)

            //badgeView.frame=(0.0, 0.0, 17.0, 17.0)

            let badgeFrameSize = badgeView.frame.size

            //badgeFrameSize=(14.0, 14.0)

            self.addSubview(self.badgeView)

            constrain(self.badgeView) {badgeView in

                badgeView.top == badgeView.superview!.top – badgeFrameSize.height/2 + self.badgeMoveDown

                badgeView.right == badgeView.superview!.right – badgeFrameSize.width/2 + self.badgeMoveRight

            }

        } else {

            self.badgeView = UIView()

            self.badgeView.hidden = true

        }

    }

}

class CreateNewButton: BadgeButton {

    var newImageView:UIImageView

    var newLabel:UILabel

    init(newImage:UIImage, newTitle:String) {

        gLog.info(“newImage=\(newImage), newTitle=\(newTitle)”)

        self.newImageView = UIImageView()

        self.newLabel = UILabel()

        super.init(frame: CGRectZero)

        //1. image view

        self.addSubview(self.newImageView)

        self.newImageView.image = newImage

        constrain(newImageView) {newImageView in

            newImageView.top == newImageView.superview!.top + 16

            newImageView.height == self.newImageView.image!.size.height

            newImageView.centerX == newImageView.superview!.centerX

            newImageView.width <= newImageView.superview!.width

        }

        //3. new title label

        self.addSubview(self.newLabel)

        self.newLabel.text = newTitle

        self.newLabel.textAlignment = .Center

        self.newLabel.font = UIFont.systemFontOfSize(10)

        self.newLabel.textColor = UIColor(hexString: “#323232”)!

        constrain(newLabel, newImageView) {newLabel, newImageView in

            newLabel.top == newImageView.bottom + 10

            newLabel.height == 16

            newLabel.width <= newLabel.superview!.width

            newLabel.centerX == newLabel.superview!.centerX

        }

    }

    required init?(coder aDecoder: NSCoder) {

        fatalError(“init(coder:) has not been implemented”)

    }

}

    var messageBadgeButton:BadgeButton

    var toCompleteButton:CreateNewButton

        self.toCompleteButton = CreateNewButton(newImage: UIImage(named: “new_toComplete”)!, newTitle: “待完善客户”)

        self.toCompleteButton.badgeMoveRight = -26

        self.toCompleteButton.badgeMoveDown = 18

        self.messageBadgeButton = BadgeButton()

        //let messageBadgeButton:BadgeButton = BadgeButton()

        messageBadgeButton.frame = CGRectMake(0, 0, NaviMessageImage.size.width, NaviMessageImage.size.height)

        messageBadgeButton.setImage(NaviMessageImage, forState: UIControlState.Normal)

        messageBadgeButton.addTarget(self, action: #selector(self.showMessageVC), forControlEvents: UIControlEvents.TouchUpInside)

        messageBadgeButton.badgeMoveDown = 3

        messageBadgeButton.badgeMoveRight = 0

        messageBadgeButton.badgeInt = 6

        //for debug

//        messageBadgeButton.backgroundColor = UIColor.greenColor()

        let messageBarItem = UIBarButtonItem(customView: messageBadgeButton)

        SingletonMainVC().navigationItem.setRightBarButtonItem(messageBarItem, animated: false)

        //2.2 new to complete

        toCompleteButton.badgeInt = 6

        toCompleteButton.addTarget(self, action: #selector(self.toCompleteCustomer(_:)), forControlEvents: UIControlEvents.TouchUpInside)

        self.newView.addSubview(toCompleteButton)

        constrain(toCompleteButton, newCustomerButton) {toCompleteButton, newCustomerButton in

            toCompleteButton.top == toCompleteButton.superview!.top

            toCompleteButton.left == newCustomerButton.right

            toCompleteButton.width == NewButtonWidth

            toCompleteButton.bottom == toCompleteButton.superview!.bottom

        }

    func showMessageVC(sender:UIButton){

        gLog.info(“sender=\(sender)”)

//        let messageVC = MessageViewController()

//        self.showViewController(messageVC, sender: messageVC)

        //for debug

        if messageBadgeButton.badgeInt == 6 {

            messageBadgeButton.badgeInt = 4

        } else if messageBadgeButton.badgeInt == 4 {

            messageBadgeButton.badgeInt = 0

        } else if messageBadgeButton.badgeInt == 0 {

            messageBadgeButton.badgeInt = 6

        }

    }

    func toCompleteCustomer(sender:UIButton){

        gLog.info(“”)

        self.toCompleteButton.badgeInt += 1

//        self.toCompleteButton.badgeInt -= 1

    }

达到如下效果:

算是自己实现了对应的扩展,支持普通的button加上badge值了。

更新更全代码可参考:

https://github.com/crifan/crifanLib/blob/master/swift/UI/Button/BadgeButton/BadgeButton.swift

https://github.com/crifan/crifanLib/blob/master/swift/UI/Button/BadgeButton/BadgeButtonDemo.swift

转载请注明:在路上 » [已解决]swift带badge的UIBarButtonItem

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
60 queries in 0.086 seconds, using 18.95MB memory