SoFunction
Updated on 2025-04-12

Similar to WeChat red dot display function in iOS

Design idea: Add a category to UIView. All views can be displayed red dots as needed.

#import <UIKit/>
@interface UIView (CHRRedDot)
@property (readonly, nonatomic) CALayer * chr_redDotLayer;
/**
  The position of the center of the red dot circle and the distance between each edge.  If the distance is <=0, the distance is ignored
  */
@property (nonatomic, assign) UIEdgeInsets chr_redDotEdgeInsets;
/**
  The radius of the red dot is 4 by default
  */
@property (nonatomic, assign) CGFloat chr_redDotRadius;
/**
  The color of the red dot is 0xFF5A5A by default
  */
@property (nonatomic, strong) UIColor * chr_redDotColor;
/**
  Is the red dot displayed?
  */
@property (nonatomic, assign) BOOL chr_redDotShow;
@end
#pragma mark - method
- (void)chr_updateRedDot {
  CALayer *redDot = self.chr_redDotLayer;
  if (self.chr_redDotShow) {
    if (redDot == nil) {
      redDot = [CALayer layer];
      self.chr_redDotLayer = redDot;
      [ addSublayer:redDot];
    }
     = self.chr_redDotColor.CGColor;
    [self chr_layoutRedDot];
  } else {
    [redDot removeFromSuperlayer];
    self.chr_redDotLayer = nil;
  }
}
- (void)chr_layoutRedDot {
  CALayer *redDot = self.chr_redDotLayer;
  if (redDot == nil) return;
  CGFloat radius = self.chr_redDotRadius;
   = radius;
  UIEdgeInsets edgeInsets = self.chr_redDotEdgeInsets;
  CGFloat originX =  &lt;= 0 ?  - radius :  -  + radius;
  CGFloat originY =  &lt;= 0 ?  - radius :  -  + radius;
  CGFloat length = radius * 2;
   = CGRectMake(originX, originY, length, length);
}

The above is the similar WeChat red dot display function in iOS introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!