您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

iOS 實現類微信紅點提示的通用方案

編輯:iOS 技巧大全
[摘要]本文分享一個通過 UIView Category 實現紅點提示的通用方案,支持自定義位置、邊距、半徑與顏色,任意視圖都可直接使用。

設計思路很簡單:給 UIView 增加一個分類,這樣項目中所有視圖都能按需顯示紅點,無需為每個需要角標的控件單獨寫邏輯。

實現上,紅點本質是一個添加到父視圖 layer 上的 CALayer,通過一組屬性控制它的位置、大小與顏色,再由外部的布爾值決定顯示或移除。

頭文件聲明

#import <UIKit/UIKit.h>

@interface UIView (CHRRedDot)

@property (readonly, nonatomic) CALayer *chr_redDotLayer;

/** 紅點圓心位置,與各個邊之間的距離。如果距離 <= 0,則忽略該邊的距離計算 */
@property (nonatomic, assign) UIEdgeInsets chr_redDotEdgeInsets;

/** 紅點半徑,默認為 4 */
@property (nonatomic, assign) CGFloat chr_redDotRadius;

/** 紅點顏色,默認為 0xFF5A5A */
@property (nonatomic, strong) UIColor *chr_redDotColor;

/** 紅點是否顯示 */
@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;
            [self.layer addSublayer:redDot];
        }
        redDot.backgroundColor = self.chr_redDotColor.CGColor;
        [self chr_layoutRedDot];
    } else {
        [redDot removeFromSuperlayer];
        self.chr_redDotLayer = nil;
    }
}

// 計算紅點的 frame
- (void)chr_layoutRedDot {
    CALayer *redDot = self.chr_redDotLayer;
    if (redDot == nil) return;

    CGFloat radius = self.chr_redDotRadius;
    redDot.cornerRadius = radius;

    UIEdgeInsets edgeInsets = self.chr_redDotEdgeInsets;

    // 當對應邊距 <= 0 時,表示以該邊為基準定位(左上角)
    // 否則表示距離該邊的距離(右上角 / 左下角 / 右下角)
    CGFloat originX = edgeInsets.right <= 0
        ? edgeInsets.left - radius
        : self.bounds.size.width - edgeInsets.right + radius;

    CGFloat originY = edgeInsets.bottom <= 0
        ? edgeInsets.top - radius
        : self.bounds.size.height - edgeInsets.bottom + radius;

    CGFloat length = radius * 2;
    redDot.frame = CGRectMake(originX, originY, length, length);
}

使用方式

使用時只需一行:

// 顯示紅點
someView.chr_redDotShow = YES;
[someView chr_updateRedDot];

// 隱藏紅點
someView.chr_redDotShow = NO;
[someView chr_updateRedDot];

這種封裝方式的好處是職責清晰、可複用性強。無論是 tabBar 按鈕、導航欄項還是列表 cell 上的子控件,都能統一接入同一套紅點邏輯。如果後續需要支持顯示數字而非圓點,也可以在此基礎上擴展一個 label 子層。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved