博客> Swift 给UITabbarItem 添加小红点
Swift 给UITabbarItem 添加小红点
2018-09-20 04:19 评论:0 阅读:161 十九灵童
ios UITabBarItem 小红点

搜索了网上现有的方法,是直接在tabbar上加view,但在iPad上计算出的位置有偏移。 于是决定在每个item 对应的view上加红点。考虑到item的viewClass 可能会变,需遍历出最有可能是item对应的view。

给 TabbarController 添加扩展方法: func setRedDot(hidden:Bool,at index:Int){ var viewAsClasses:[String:[UIView]] = [:] for subview in self.tabBar.subviews { let viewClass = "cls_(subview.classForCoder)" var existViews = viewAsClasses[viewClass] ?? [] existViews.append(subview) viewAsClasses.updateValue(existViews, forKey: viewClass) } var posibaleItemViews:[UIView] = [] // swiftlint:disable for_where for value in viewAsClasses.values { if value.count > posibaleItemViews.count { posibaleItemViews = value } } var itemView:UIView? if posibaleItemViews.count > index { itemView = posibaleItemViews[index] } if itemView == nil { return } let dotTag = 8998 + index var badgeView = itemView!.viewWithTag(dotTag) badgeView?.removeFromSuperview() if !hidden { if badgeView == nil { badgeView = UIView.init() badgeView?.tag = dotTag badgeView?.layer.cornerRadius = 5 badgeView?.backgroundColor = UIColor.red } itemView!.addSubview(badgeView!) let x = Int(0.618 itemView!.frame.size.width) let y = Int(0.1 itemView!.frame.size.height) badgeView!.frame = CGRect.init(x: x , y: y , width: 10, height: 10) } }

收藏
0
sina weixin mail 回到顶部