iOS 叠加视图

  • 内容
  • 评论
  • 相关

效果类似

//
//  AvatarListView.h
//  UniversalApp
//
//  Created by voidcat on 2024/4/13.
//  Copyright © 2024 voidcat. All rights reserved.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

// 头像视图类
@interface AvatarView : UIView

@property (nonatomic, strong) UIImageView *avatarImageView;
@property (nonatomic, assign) CGFloat overlappingOffset;

- (instancetype)initWithImage:(UIImage *)image;

@end

@interface AvatarListView : UIView
- (void)addAvatarWithImage:(UIImage *)image;
- (void)removeLastAvatar;
@end

NS_ASSUME_NONNULL_END

#import "AvatarListView.h"

// 头像视图类实现
@implementation AvatarView

- (instancetype)initWithImage:(UIImage *)image {
    self = [super initWithFrame:CGRectMake(0, 0, 50, 50)];
    if (self) {
        _avatarImageView = [[UIImageView alloc] initWithImage:image];
        _avatarImageView.frame = self.bounds;
        _avatarImageView.layer.cornerRadius = self.frame.size.width / 2;
        _avatarImageView.clipsToBounds = YES;
        [self addSubview:_avatarImageView];
        
        _overlappingOffset = 10.0f;
    }
    return self;
}

@end

@interface AvatarListView ()

@property (nonatomic, strong) NSMutableArray<AvatarView *> *avatarViews;
@property (nonatomic, assign) CGFloat overlappingOffset;

@end


@implementation AvatarListView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _avatarViews = [NSMutableArray array];
        _overlappingOffset = 10.0f;
    }
    return self;
}

- (void)addAvatarWithImage:(UIImage *)image {
    AvatarView *avatarView = [[AvatarView alloc] initWithImage:image];
    [self addSubview:avatarView];
    
    CGFloat x = 0;
    if (_avatarViews.count > 0) {
        x = _avatarViews.lastObject.frame.origin.x + _avatarViews.lastObject.frame.size.width - _overlappingOffset;
    }
    avatarView.frame = CGRectMake(x, 0, 50, 50);
    
    [_avatarViews addObject:avatarView];
}

- (void)removeLastAvatar {
    if (_avatarViews.count > 0) {
        AvatarView *lastAvatar = _avatarViews.lastObject;
        [lastAvatar removeFromSuperview];
        [_avatarViews removeLastObject];
    }
}

@end

使用

    AvatarListView *avatarListView = [[AvatarListView alloc] initWithFrame:CGRectMake(20, 100, 300, 50)];
    [self addSubview:avatarListView];
    
    [avatarListView addAvatarWithImage:[UIImage imageNamed:@"默认头像"]];
    [avatarListView addAvatarWithImage:[UIImage imageNamed:@"默认头像"]];
    [avatarListView addAvatarWithImage:[UIImage imageNamed:@"默认头像"]];

评论

0条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注