// // XPHomeViewController.m // YuMi // // Created by YuMi on 2021/11/29. // #import "XPHomePartyViewController.h" ///Third #import #import ///Tool #import "YUMIMacroUitls.h" #import "DJDKMIMOMColor.h" #import "NSArray+Safe.h" ///Model #import "HomeRecommendRoomModel.h" ///View #import "XPNewHomePartyCollectionViewCell.h" #import "XPGuildEmptyCollectionViewCell.h" #import "XPPartyRoomItemCollectionViewCell.h" #import "XPBlankRoomModel.h" #import "XPWeakTimer.h" ///P #import "XPHomePresenter.h" #import "XPHomeProtocol.h" ///VC #import "XPRoomViewController.h" #import #import "HomeBannerInfoModel.h" // 布局类型持久化 key static NSString * const kHomeLayoutTypeKey = @"kHomeLayoutTypeKey"; @interface HomePartyBannerCell : UICollectionViewCell @property (nonatomic, strong) SDCycleScrollView *bannerView; @property (nonatomic, copy) NSArray *bannerInfoList; @property (nonatomic, copy) void(^didTapBannerItem)(HomeBannerInfoModel *model); @end @implementation HomePartyBannerCell - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self.contentView addSubview:self.bannerView]; [self.bannerView mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.mas_equalTo(self.contentView); }]; } return self; } - (void)setBannerInfoList:(NSArray *)bannerInfoList { _bannerInfoList = bannerInfoList; NSMutableArray *picArray = @[].mutableCopy; for (HomeBannerInfoModel *model in bannerInfoList) { if (![NSString isEmpty:model.bannerPic]) { NSCharacterSet *allowedCharacters = [NSCharacterSet URLFragmentAllowedCharacterSet]; NSString *encodedURLString = [model.bannerPic stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters]; [picArray addObject:encodedURLString]; } } self.bannerView.imageURLStringsGroup = picArray.copy; self.bannerView.autoScroll = YES; } - (SDCycleScrollView *)bannerView { if (!_bannerView) { _bannerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectZero delegate:self placeholderImage:[UIImageConstant defaultBannerPlaceholder]]; _bannerView.backgroundColor = [UIColor clearColor]; _bannerView.layer.cornerRadius = 12; _bannerView.layer.masksToBounds = YES; _bannerView.showPageControl = YES; _bannerView.autoScrollTimeInterval = 5.0; _bannerView.pageControlDotSize = CGSizeMake(3, 3); _bannerView.pageDotColor = [UIColor lightGrayColor]; _bannerView.currentPageDotColor = [UIColor darkGrayColor]; _bannerView.bannerImageViewContentMode = UIViewContentModeScaleToFill; if (isMSRTL()) { for (UIView *subView in _bannerView.subviews) { subView.semanticContentAttribute = UISemanticContentAttributeForceLeftToRight; } } } return _bannerView; } - (void)prepareForReuse { [super prepareForReuse]; // 安全释放:停止轮播并清理数据,避免离屏仍占用内存/CPU self.bannerView.autoScroll = NO; self.bannerView.imageURLStringsGroup = nil; } - (void)stopAndRelease { // 离屏时显式停止以释放资源 self.bannerView.autoScroll = NO; } // 进入可见区域后恢复滚动(由 VC 调用) - (void)resumeIfNeeded { if (self.bannerView.imageURLStringsGroup.count > 0) { self.bannerView.autoScroll = YES; } } #pragma mark - SDCycleScrollViewDelegate - (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index { HomeBannerInfoModel * bannerInfo = [self.bannerInfoList xpSafeObjectAtIndex:index]; if (bannerInfo && self.didTapBannerItem) { self.didTapBannerItem(bannerInfo); } } @end @interface XPHomePartyViewController () ///数据源 @property (nonatomic,strong) NSMutableArray *datasource; ///列表 @property (nonatomic,strong) UICollectionView *collectionView; ///当前的页数 @property (nonatomic,assign) int page; ///没有新的数据了 @property (nonatomic,assign) BOOL hasNoMoreData; ///布局模式:YES为两列,NO为一列 @property (nonatomic,assign) BOOL isTwoColumnLayout; @end @implementation XPHomePartyViewController - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (BOOL)isHiddenNavBar { return YES; } - (XPHomePresenter *)createPresenter { return [[XPHomePresenter alloc] init]; } - (void)viewDidLoad { [super viewDidLoad]; [self loadLayoutTypeFromCache]; [self initSubViews]; [self initSubViewConstraints]; [self setupLayoutNotification]; [self updateCollectionViewLayout]; } - (void)starBeginHeaderRefresh { } #pragma mark - Private Method - (void)initSubViews { self.view.backgroundColor = [UIColor clearColor]; [self.view addSubview:self.collectionView]; } - (void)loadLayoutTypeFromCache { // 从 UserDefaults 读取缓存的布局类型;若无记录,则默认两列以降低进入内存消耗 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; id storedValue = [defaults objectForKey:kHomeLayoutTypeKey]; if (storedValue == nil) { self.isTwoColumnLayout = YES; // 默认两列 [defaults setBool:YES forKey:kHomeLayoutTypeKey]; [defaults synchronize]; } else { self.isTwoColumnLayout = [storedValue boolValue]; } } - (void)saveLayoutTypeToCache { // 保存当前布局类型到 UserDefaults [[NSUserDefaults standardUserDefaults] setBool:self.isTwoColumnLayout forKey:kHomeLayoutTypeKey]; [[NSUserDefaults standardUserDefaults] synchronize]; } - (void)setupLayoutNotification { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleLayoutToggle) name:@"kHomeLayoutToggle" object:nil]; } - (void)handleLayoutToggle { self.isTwoColumnLayout = !self.isTwoColumnLayout; [self saveLayoutTypeToCache]; [self processCurrentDataSourceForLayout]; [self updateCollectionViewLayout]; [self.collectionView reloadData]; } - (void)processCurrentDataSourceForLayout { if (self.datasource.count == 0) return; // 先移除所有占位model和banner,重新构建数据源 NSMutableArray *nonBannerItems = [NSMutableArray array]; NSArray *bannerData = nil; for (id item in self.datasource) { if ([item isKindOfClass:[NSArray class]]) { bannerData = item; // 保存banner数据 } else if (![item isKindOfClass:[XPBlankRoomModel class]]) { [nonBannerItems addObject:item]; // 保存非banner、非占位的数据 } } // 根据布局模式处理数据 if (self.isTwoColumnLayout) { // 两列布局:为奇数个非banner元素添加占位model NSInteger nonBannerCount = nonBannerItems.count; // 如果非banner元素为奇数个,添加占位model if (nonBannerCount % 2 != 0) { [nonBannerItems addObject:[[XPBlankRoomModel alloc] init]]; } } // 重新构建数据源:先添加非banner数据,再插入banner NSMutableArray *newDataSource = [NSMutableArray arrayWithArray:nonBannerItems]; if (bannerData) { // 根据布局模式确定banner插入位置:两列布局位置6,一列布局位置5 NSInteger insertIndex = self.isTwoColumnLayout ? 6 : 5; if (newDataSource.count < insertIndex) { [newDataSource addObject:bannerData]; } else { [newDataSource insertObject:bannerData atIndex:insertIndex]; } } self.datasource = newDataSource; } - (void)updateCollectionViewLayout { if ([self.collectionView.collectionViewLayout isKindOfClass:[MSBaseRTLFlowLayout class]]) { MSBaseRTLFlowLayout *layout = (MSBaseRTLFlowLayout *)self.collectionView.collectionViewLayout; CGFloat topInset = self.isTwoColumnLayout ? 4 : 20; CGFloat bottomInset = self.isTwoColumnLayout ? 40 : 0; layout.sectionInset = UIEdgeInsetsMake(topInset, 15, bottomInset, 15); } } - (NSArray *)processDataSourceForLayout:(NSArray *)originalList { if (originalList.count == 0) return originalList; if (self.isTwoColumnLayout) { // 两列布局:为奇数个非banner元素添加占位model NSMutableArray *processedDataSource = [NSMutableArray arrayWithArray:originalList]; NSInteger nonBannerCount = 0; for (id item in originalList) { if (![item isKindOfClass:[NSArray class]]) { nonBannerCount++; } } // 如果非banner元素为奇数个,添加占位model if (nonBannerCount % 2 != 0) { // 找到最后一个非banner元素的位置,在其后插入占位model NSInteger insertIndex = -1; for (NSInteger i = processedDataSource.count - 1; i >= 0; i--) { id item = processedDataSource[i]; if (![item isKindOfClass:[NSArray class]]) { insertIndex = i + 1; break; } } if (insertIndex >= 0) { [processedDataSource insertObject:[[XPBlankRoomModel alloc] init] atIndex:insertIndex]; } else { [processedDataSource addObject:[[XPBlankRoomModel alloc] init]]; } } return processedDataSource; } else { // 一列布局:移除所有占位model NSMutableArray *processedDataSource = [NSMutableArray array]; for (id item in originalList) { if (![item isKindOfClass:[XPBlankRoomModel class]]) { [processedDataSource addObject:item]; } } return processedDataSource; } } - (void)initSubViewConstraints { [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(0); make.leading.trailing.bottom.equalTo(self.view); }]; MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)]; footer.stateLabel.textColor = [DJDKMIMOMColor secondTextColor]; footer.stateLabel.font = [UIFont systemFontOfSize:10.0]; self.collectionView.mj_footer = footer; } #pragma mark - 刷新的方法 - (void)headerRefresh { self.page = 1; if ([self.tagModel.id isEqualToString:@"-11"]) { [self.presenter getMyCollectRooms:self.page]; } else if ([self.tagModel.id isEqualToString:@"-12"]) { [self.presenter getMyRecentRooms:self.page]; } else if([self.tagModel.id isEqualToString:@"-1"]){ [self.presenter getHomePersonalRoomList]; } else{ [XNDJTDDLoadingTool showLoading]; [self.presenter loadSecondBanner]; } } -(void)footerRefresh{ self.page++; if ([self.tagModel.id isEqualToString:@"-11"]) { [self.presenter getMyCollectRooms:self.page]; } else if ([self.tagModel.id isEqualToString:@"-12"]) { [self.presenter getMyRecentRooms:self.page]; } else if([self.tagModel.id isEqualToString:@"-1"]){ [self.collectionView.mj_footer endRefreshing]; }else{ [self.presenter getRecommendRoomList:self.tagModel.id page:self.page]; } } #pragma mark - UICollectionViewDelegate And UICollectionViewDataSource - (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ if(self.datasource.count == 0){ XPGuildEmptyCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([XPGuildEmptyCollectionViewCell class]) forIndexPath:indexPath]; [cell setConstraints]; [cell setTitle:YMLocalizedString(@"XPGuildEmptyCollectionViewCell0")]; return cell; } id item = [self.datasource xpSafeObjectAtIndex:indexPath.row]; // 检查是否为占位 model if ([item isKindOfClass:[XPBlankRoomModel class]]) { XPPartyRoomItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[XPPartyRoomItemCollectionViewCell blankCellID] forIndexPath:indexPath]; cell.alpha = 0.0; cell.contentView.hidden = YES; return cell; } if ([item isKindOfClass:[NSArray class]]) { HomePartyBannerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([HomePartyBannerCell class]) forIndexPath:indexPath]; cell.bannerInfoList = item; @kWeakify(self); [cell setDidTapBannerItem:^(HomeBannerInfoModel *model) { @kStrongify(self); if (self.didTapBannerItem) { self.didTapBannerItem(model); } }]; return cell; } else { if (self.isTwoColumnLayout) { XPPartyRoomItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[XPPartyRoomItemCollectionViewCell itemCellID] forIndexPath:indexPath]; cell.roomInfo = [self.datasource xpSafeObjectAtIndex:indexPath.row]; return cell; } else { XPNewHomePartyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([XPNewHomePartyCollectionViewCell class]) forIndexPath:indexPath]; cell.roomInfo = [self.datasource xpSafeObjectAtIndex:indexPath.row]; return cell; } } } - (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { if(self.datasource.count == 0) { return 1; } return self.datasource.count; } - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ if(self.datasource.count == 0) { return self.collectionView.frame.size; } id item = [self.datasource xpSafeObjectAtIndex:indexPath.row]; // 计算尺寸:两列模式非 banner 为正方形半宽;banner 始终全宽且固定高 BOOL isBanner = [item isKindOfClass:[NSArray class]]; if (isBanner) { return CGSizeMake(kGetScaleWidth(345), kGetScaleWidth(105)); } if (self.isTwoColumnLayout || [item isKindOfClass:[XPBlankRoomModel class]]) { CGFloat width = kGetScaleWidth(345)/2; CGFloat height = width + 8; return CGSizeMake(width, height); } return CGSizeMake(kGetScaleWidth(345), kGetScaleWidth(92)); } - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath { // 离屏安全释放:对不同类型 cell 做最小必要释放 if ([cell isKindOfClass:[HomePartyBannerCell class]]) { HomePartyBannerCell *bannerCell = (HomePartyBannerCell *)cell; [bannerCell stopAndRelease]; } else if ([cell isKindOfClass:[XPNewHomePartyCollectionViewCell class]]) { // 触发其内部 prepareForReuse 等价释放 [cell prepareForReuse]; } else if ([cell isKindOfClass:[XPPartyRoomItemCollectionViewCell class]]) { [cell prepareForReuse]; } } - (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath { // 进入可见区:如为 banner,恢复自动滚动(若有数据) if ([cell isKindOfClass:[HomePartyBannerCell class]]) { HomePartyBannerCell *bannerCell = (HomePartyBannerCell *)cell; [bannerCell resumeIfNeeded]; } } -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ id item = [self.datasource xpSafeObjectAtIndex:indexPath.row]; // 跳过占位 model 的点击 if ([item isKindOfClass:[XPBlankRoomModel class]]) { return; } if ([item isKindOfClass:[HomePlayRoomModel class]]) { HomePlayRoomModel * roomInfo = (HomePlayRoomModel *)item; if (roomInfo.uid.length > 0) { [XPRoomViewController openRoom:roomInfo.uid viewController:self]; } } } #pragma mark - XPHomeProtocol - (void)getHomePersonalRoomListSuccess:(NSArray *)list{ [[NSNotificationCenter defaultCenter] postNotificationName:@"khomeVCRefreshComplete" object:nil]; for (HomePlayRoomModel *model in list) { model.width = [UILabel getWidthWithText:@(model.onlineNum).stringValue height:kGetScaleWidth(12) font:kFontBold(10)]+1; } self.datasource = [NSMutableArray arrayWithArray:[self processDataSourceForLayout:list]]; [self.collectionView reloadData]; } - (void)getHomePersonalRoomListFail{ [[NSNotificationCenter defaultCenter] postNotificationName:@"khomeVCRefreshComplete" object:nil]; } - (NSMutableArray *)insertBannerData:(NSArray *)firstPageList { // 先处理数据布局(在插入banner之前) NSArray *processedList = [self processDataSourceForLayout:firstPageList]; NSMutableArray *mutableArrayA = [processedList mutableCopy]; if (self.bannerInfoList.count > 0) { // 根据布局模式确定banner插入位置:两列布局位置6,一列布局位置5 NSInteger insertIndex = self.isTwoColumnLayout ? 6 : 5; if (mutableArrayA.count < insertIndex) { [mutableArrayA addObject:self.bannerInfoList]; } else { [mutableArrayA insertObject:self.bannerInfoList atIndex:insertIndex]; } } return mutableArrayA; } - (void)getHomeRecommendRoomListSuccess:(NSArray *)list{ for (HomePlayRoomModel *model in list) { model.width = [UILabel getWidthWithText:@(model.onlineNum).stringValue height:kGetScaleWidth(12) font:kFontBold(10)]+1; } if(self.page == 1){ self.datasource = [self insertBannerData:list]; }else{ NSArray *processedList = [self processDataSourceForLayout:list]; [self.datasource addObjectsFromArray:processedList]; } [self.collectionView reloadData]; [[NSNotificationCenter defaultCenter]postNotificationName:@"khomeVCRefreshComplete" object:nil]; [self.collectionView.mj_footer endRefreshing]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [XNDJTDDLoadingTool hideHUD]; }); } - (void)getHomeSecondBannerSuccess:(NSArray *)banners { self.bannerInfoList = banners; [self.presenter getRecommendRoomList:self.tagModel.id page:self.page]; } - (void)getHomeRecommendRoomListFail:(NSString *)message{ self.page--; [self.collectionView.mj_footer endRefreshing]; [[NSNotificationCenter defaultCenter]postNotificationName:@"khomeVCRefreshComplete" object:nil]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [XNDJTDDLoadingTool hideHUD]; }); } - (void)getMineCollectRoomsSuccess:(NSArray *)rooms { [[NSNotificationCenter defaultCenter]postNotificationName:@"khomeVCRefreshComplete" object:nil]; [self.collectionView.mj_footer endRefreshing]; for (HomePlayRoomModel *model in rooms) { model.width = [UILabel getWidthWithText:@(model.onlineNum).stringValue height:kGetScaleWidth(12) font:kFontBold(10)] + 1; } if(self.page == 1){ self.datasource = [NSMutableArray arrayWithArray:[self processDataSourceForLayout:rooms]]; }else{ NSArray *processedList = [self processDataSourceForLayout:rooms]; [self.datasource addObjectsFromArray:processedList]; } [self.collectionView reloadData]; } - (void)getMineRecentRoomsSuccess:(NSArray *)rooms { [[NSNotificationCenter defaultCenter]postNotificationName:@"khomeVCRefreshComplete" object:nil]; [self.collectionView.mj_footer endRefreshing]; for (HomePlayRoomModel *model in rooms) { model.width = [UILabel getWidthWithText:@(model.onlineNum).stringValue height:kGetScaleWidth(12) font:kFontBold(10)] + 1; } if(self.page == 1){ self.datasource = [NSMutableArray arrayWithArray:[self processDataSourceForLayout:rooms]]; }else{ NSArray *processedList = [self processDataSourceForLayout:rooms]; [self.datasource addObjectsFromArray:processedList]; } [self.collectionView reloadData]; } #pragma mark - JXPagingViewListViewDelegate - (UIScrollView *)listScrollView { return self.collectionView; } - (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback { self.scrollCallback = callback; } - (UIView *)listView { return self.view; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { if(self.scrollCallback){ self.scrollCallback(scrollView); } } - (void)listDidAppear { if (self.didAppear && self.tagModel) { self.didAppear(self.tagModel); } } #pragma mark - Getters And Setters -(void)setTagModel:(PIHomeCategoryTitleModel *)tagModel{ _tagModel = tagModel; @kWeakify(self); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ @kStrongify(self); [self headerRefresh]; }); } - (UICollectionView *)collectionView{ if (!_collectionView) { MSBaseRTLFlowLayout *layout = [[MSBaseRTLFlowLayout alloc] init]; layout.minimumInteritemSpacing = kGetScaleWidth(0); layout.minimumLineSpacing = kGetScaleWidth(18); CGFloat topInset = self.isTwoColumnLayout ? 4 : 20; layout.sectionInset = UIEdgeInsetsMake(topInset, 15, 0, 15); _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout]; _collectionView.backgroundColor = [UIColor clearColor]; _collectionView.dataSource = self; _collectionView.delegate = self; _collectionView.tag = 78574; [_collectionView registerClass:[XPNewHomePartyCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([XPNewHomePartyCollectionViewCell class])]; [_collectionView registerClass:[XPGuildEmptyCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([XPGuildEmptyCollectionViewCell class])]; [_collectionView registerClass:[HomePartyBannerCell class] forCellWithReuseIdentifier:NSStringFromClass([HomePartyBannerCell class])]; [_collectionView registerClass:[XPPartyRoomItemCollectionViewCell class] forCellWithReuseIdentifier:[XPPartyRoomItemCollectionViewCell blankCellID]]; [_collectionView registerClass:[XPPartyRoomItemCollectionViewCell class] forCellWithReuseIdentifier:[XPPartyRoomItemCollectionViewCell itemCellID]]; } return _collectionView; } - (NSMutableArray *)datasource { if (!_datasource) { _datasource = [NSMutableArray array]; } return _datasource; } @end