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

      在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)





猜你喜欢

转载自blog.csdn.net/qq_37269542/article/details/70859374