swift封装一个继承UILabel的红色小圆圈用来显示消息的个数

29 篇文章 1 订阅
27 篇文章 0 订阅

      在app中往往会需要去显示一些通知的信息的个数,往往是在图标上面加一个红色的小圆圈,然后在上面动态的显示在消息的个数,就像微信中提示信息的个数一样。效果图如下:

   

现将如图红色圆圈的中的数字显示样式封装如下:

import UIKit

class Info: UILabel {
  var defaultInsets = CGSize(width: 2, height: 2)
  var actualInsets = CGSize()
  
  convenience init() {
    self.init(frame: CGRect())
  }
  
  override init(frame: CGRect) {
    super.init(frame: frame)
    
    setup()
  }
  
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    
    setup()
  }
  
  private func setup() {
    translatesAutoresizingMaskIntoConstraints = false
    
    layer.backgroundColor = UIColor.redColor().CGColor
    textColor = UIColor.whiteColor()
    
    // Shadow
    layer.shadowOpacity = 0.5
    layer.shadowOffset = CGSize(width: 0, height: 0)
    layer.shadowRadius = 0.5
    layer.shadowColor = UIColor.blackColor().CGColor
    
    self.textAlignment = NSTextAlignment.Center
  }
  
  // Add custom insets
  // --------------------
  override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
    let rect = super.textRectForBounds(bounds, limitedToNumberOfLines: numberOfLines)
    
    actualInsets = defaultInsets
    let rectWithDefaultInsets = CGRectInset(rect, -actualInsets.width, -actualInsets.height)
    
    // If width is less than height
    // Adjust the width insets to make it look round
    if rectWithDefaultInsets.width < rectWithDefaultInsets.height {
      actualInsets.width = (rectWithDefaultInsets.height - rect.width) / 2
    }
    
    return CGRectInset(rect, -actualInsets.width, -actualInsets.height)
  }
  
  override func drawTextInRect(rect: CGRect) {
    
    layer.cornerRadius = rect.height / 2
    
    let insets = UIEdgeInsets(
      top: actualInsets.height,
      left: actualInsets.width,
      bottom: actualInsets.height,
      right: actualInsets.width)
    
    let rectWithoutInsets = UIEdgeInsetsInsetRect(rect, insets)
    
    super.drawTextInRect(rectWithoutInsets)
  }
}

调用使用的代码如下:

例如:

var noticeNum:Info!
noticeNum = Info(frame: CGRect(x:100, y:100, width : 25, height : 25))
noticeNum.text = "31"
self.View.addSubview(noticeNum)





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值