-
-
Save MacMark/7ca92b419a2bd279a40e7264a4ef013f to your computer and use it in GitHub Desktop.
UITabBar+Badge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
fileprivate let tabBarItemTag: Int = 10090 | |
extension UITabBar { | |
public func addItemBadge(atIndex index: Int) { | |
guard let itemCount = self.items?.count, itemCount > 0 else { | |
return | |
} | |
guard index < itemCount else { | |
return | |
} | |
removeItemBadge(atIndex: index) | |
let badgeView = UIView() | |
badgeView.tag = tabBarItemTag + Int(index) | |
badgeView.layer.cornerRadius = 5 | |
badgeView.backgroundColor = UIColor.red | |
let tabFrame = self.frame | |
let percentX = (CGFloat(index) + 0.56) / CGFloat(itemCount) | |
let x = (percentX * tabFrame.size.width).rounded(.up) | |
let y = (CGFloat(0.1) * tabFrame.size.height).rounded(.up) | |
badgeView.frame = CGRect(x: x, y: y, width: 10, height: 10) | |
addSubview(badgeView) | |
} | |
//return true if removed success. | |
@discardableResult | |
public func removeItemBadge(atIndex index: Int) -> Bool { | |
for subView in self.subviews { | |
if subView.tag == (tabBarItemTag + index) { | |
subView.removeFromSuperview() | |
return true | |
} | |
} | |
return false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment