APP中总会出现收到系统消息,按钮右上方出现带数字的小红点,特写一个demo以此记录
首先自定义一个UIButton,在UIButton中添加一个Label,存放消息数目
//
// BadgeNumBtn.swift
//
//
import UIKit
class BadgeNumBtn: UIButton {
private static let kInsets = UIEdgeInsets(top: 4, left: 3, bottom: 4, right: 3)
private static let kFont = UIFont.systemFont(ofSize: 12)
var badgeLabelNum = 0 {
willSet {
if newValue > 0 {
badgeLabel.text = "\(newValue)"
badgeLabel.backgroundColor = UIColor.red
badgeLabel.textColor = UIColor.white
badgeLabel.sizeToFit()
} else {
badgeLabel.text = ""
badgeLabel.backgroundColor = UIColor.clear
badgeLabel.textColor = UIColor.clear
}
}
}
private lazy var badgeLabel: UILabel = {
let badgeLabel = UILabel()
badgeLabel.textAlignment = .center
badgeLabel.layer.masksToBounds = true
badgeLabel.font = kFont
return badgeLabel
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(badgeLabel)
}
required init?(coder aDecoder: NSCoder) {fatalError("init(coder:) has not been implemented")}
override func layoutSubviews() {
super.layoutSubviews()
badgeLabel.frame = CGRect(x: 0, y: 0, width:badgeLabel.bounds.size.width + BadgeNumBtn.kInsets.top , height: badgeLabel.bounds.size.width + BadgeNumBtn.kInsets.top * 2)
badgeLabel.center = CGPoint(x: self.bounds.size.width, y: 0)
badgeLabel.layer.cornerRadius = badgeLabel.bounds.size.width * 0.5
}
}
使用方法直接继承自定义的BadgeButton,将消息数设置即可
override func viewDidLoad() {
super.viewDidLoad()
var badgeBtn = BadgeNumBtn()//初始化
//不带参
badgeBtn.addTarget(self, action: #selector(badgeBtnClick(_:)), for: .touchUpInside)
view.addSubview(badgeBtn)
badgeBtn.backgroundColor = UIColor.cyan
badgeBtn.snp.makeConstraints { (make) in
make.right.equalTo(self.view).offset(-20)
make.top.equalTo(self.view).offset(80)
make.width.equalTo(100)
make.height.equalTo(40)
}
badgeBtn.badgeLabelNum = 10
codeView.addSubview(randomCaptchaView)
randomCaptchaView.snp.makeConstraints { (make) in
make.edges.equalTo(self.codeView)
}
}
func badgeBtnClick(_ sender: BadgeNumBtn){
sender.badgeLabelNum -= 1
}