extension UIView {
static let buttonBadgeTag = 889
func showBadge(badgeNum: Int, maxNum: Int = 999, percentX: Float = 0.5, percentY: Float = 0.2) {
var badgeView: UIView?
for view in self.subviews {
if view.tag == UIView.buttonBadgeTag {
badgeView = view
}
}
if (badgeView == nil) || !(badgeView is UILabel) {
let badgeLabel = UILabel()
badgeLabel.tag = UIButton.buttonBadgeTag
badgeLabel.layer.cornerRadius = 7.5
badgeLabel.layer.masksToBounds = true
badgeLabel.layer.zPosition = 1
badgeLabel.backgroundColor = BAColor
badgeLabel.textAlignment = .center
badgeLabel.textColor = UIColor.white
let x: CGFloat = CGFloat(ceilf(percentX * Float(self.frame.size.width)));
let y: CGFloat = CGFloat(ceilf(percentY * Float(self.frame.size.height)));
let textWidth = gatwidthForComment(string: "\(badgeNum)", fontSize: 12, height: 15, n: .Regular)
if badgeNum < 10 {
badgeLabel.frame = CGRect(x: x, y: y, width: 15, height: 15);
} else {
badgeLabel.frame = CGRect(x: x, y: y, width: textWidth + 8, height: 15);
}
badgeLabel.adjustsFontSizeToFitWidth = true
badgeLabel.minimumScaleFactor = 0.5
if #available(iOS 8.2, *) {
badgeLabel.font = UIFont.systemFont(ofSize: KScaleH(10), weight: UIFont.Weight.medium)
} else {
// Fallback on earlier versions
badgeLabel.font = UIFont.systemFont(ofSize: KScaleH(10))
}
self.addSubview(badgeLabel);
badgeView = badgeLabel
}
if let badgeLabel = badgeView as? UILabel {
badgeLabel.isHidden = (badgeNum <= 0)
if badgeNum > maxNum {
badgeLabel.text = "\(maxNum)+"
} else {
badgeLabel.text = String(badgeNum)
}
}
}
}
网友评论