如何在下面顶部的集合视图中添加部分标题

2024-03-21

我正在使用带有搜索栏的集合视图。我通过 cod 添加了搜索栏,起始位置为 (0,0),从顶部开始。所以现在我的图像看起来像这样:

[![在此处输入图像描述][1]][1]

但我需要将标题转到我的搜索栏。我是通过故事板完成的。但是在运行时,我的标题名称和搜索栏具有相同的来源。我需要将标题部分放在搜索栏下方。

注意:我唱了 3 个部分标题。任何想法或代码都非常有帮助。

这是我的搜索栏代码......

#import "CollectionViewController.h"
#import "CollectionViewCell.h"
@interface CollectionViewController ()<UISearchBarDelegate>

    @property (nonatomic,strong) NSArray        *dataSource;
    @property (nonatomic,strong) NSArray        *dataSourceForSearchResult;
    @property (nonatomic)        BOOL           searchBarActive;
    @property (nonatomic)        float          searchBarBoundsY;

    @property (nonatomic,strong) UISearchBar        *searchBar;
    @property (nonatomic,strong) UIRefreshControl   *refreshControl;

@end

@implementation CollectionViewController

static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    // datasource used when user search in collectionView
    self.dataSourceForSearchResult = [NSArray new];

    // normal datasource
    self.dataSource =@[@"Modesto",@"Rebecka",@"Andria",@"Sergio",@"Robby",@"Jacob",@"Lavera",@"Theola",@"Adella",@"Garry", @"Lawanda", @"Christiana", @"Billy", @"Claretta", @"Gina", @"Edna", @"Antoinette", @"Shantae", @"Jeniffer", @"Fred", @"Phylis", @"Raymon", @"Brenna", @"Gus", @"Ethan", @"Kimbery", @"Sunday", @"Darrin", @"Ruby", @"Babette", @"Latrisha", @"Dewey", @"Della", @"Dylan", @"Francina", @"Boyd", @"Willette", @"Mitsuko", @"Evan", @"Dagmar", @"Cecille", @"Doug", @"Jackeline", @"Yolanda", @"Patsy", @"Haley", @"Isaura", @"Tommye", @"Katherine", @"Vivian"];

}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self prepareUI];
}
-(void)dealloc{
    // remove Our KVO observer
    [self removeObservers];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - actions
-(void)refreashControlAction{
    [self cancelSearching];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // stop refreshing after 2 seconds
        [self.collectionView reloadData];
        [self.refreshControl endRefreshing];
    });
}


#pragma mark - <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.searchBarActive) {
        return self.dataSourceForSearchResult.count;
    }
    return self.dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

    // Configure the cell
    if (self.searchBarActive) {
        cell.laName.text = self.dataSourceForSearchResult[indexPath.row];
    }else{
        cell.laName.text = self.dataSource[indexPath.row];
    }
    return cell;
}


#pragma mark -  <UICollectionViewDelegateFlowLayout>
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                        layout:(UICollectionViewLayout*)collectionViewLayout
        insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(self.searchBar.frame.size.height, 0, 0, 0);
}
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout*)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat cellLeg = (self.collectionView.frame.size.width/2) - 5;
    return CGSizeMake(cellLeg,cellLeg);;
}


#pragma mark - search
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
    NSPredicate *resultPredicate    = [NSPredicate predicateWithFormat:@"self contains[c] %@", searchText];
    self.dataSourceForSearchResult  = [self.dataSource filteredArrayUsingPredicate:resultPredicate];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    // user did type something, check our datasource for text that looks the same
    if (searchText.length>0) {
        // search and reload data source
        self.searchBarActive = YES;
        [self filterContentForSearchText:searchText
                                   scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                          objectAtIndex:[self.searchDisplayController.searchBar
                                                         selectedScopeButtonIndex]]];
        [self.collectionView reloadData];
    }else{
        // if text lenght == 0
        // we will consider the searchbar is not active
        self.searchBarActive = NO;
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self cancelSearching];
    [self.collectionView reloadData];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    self.searchBarActive = YES;
    [self.view endEditing:YES];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    // we used here to set self.searchBarActive = YES
    // but we'll not do that any more... it made problems
    // it's better to set self.searchBarActive = YES when user typed something
    [self.searchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    // this method is being called when search btn in the keyboard tapped
    // we set searchBarActive = NO
    // but no need to reloadCollectionView
    self.searchBarActive = NO;
    [self.searchBar setShowsCancelButton:NO animated:YES];
}
-(void)cancelSearching{
    self.searchBarActive = NO;
    [self.searchBar resignFirstResponder];
    self.searchBar.text  = @"";
}
#pragma mark - prepareVC
-(void)prepareUI{
    [self addSearchBar];
    [self addRefreshControl];
}
-(void)addSearchBar{
    if (!self.searchBar) {
        self.searchBarBoundsY = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
        self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,self.searchBarBoundsY, [UIScreen mainScreen].bounds.size.width, 44)];
        self.searchBar.searchBarStyle       = UISearchBarStyleMinimal;
        self.searchBar.tintColor            = [UIColor whiteColor];
        self.searchBar.barTintColor         = [UIColor whiteColor];
        self.searchBar.delegate             = self;
        self.searchBar.placeholder          = @"search here";

        [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor whiteColor]];

        // add KVO observer.. so we will be informed when user scroll colllectionView
        [self addObservers];
    }

    if (![self.searchBar isDescendantOfView:self.view]) {
        [self.view addSubview:self.searchBar];
    }
}

-(void)addRefreshControl{
    if (!self.refreshControl) {
        self.refreshControl                  = [UIRefreshControl new];
        self.refreshControl.tintColor        = [UIColor whiteColor];
        [self.refreshControl addTarget:self
                                action:@selector(refreashControlAction)
                      forControlEvents:UIControlEventValueChanged];
    }
    if (![self.refreshControl isDescendantOfView:self.collectionView]) {
        [self.collectionView addSubview:self.refreshControl];
    }
}
-(void)startRefreshControl{
    if (!self.refreshControl.refreshing) {
        [self.refreshControl beginRefreshing];
    }
}

#pragma mark - observer 
- (void)addObservers{
    [self.collectionView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}
- (void)removeObservers{
    [self.collectionView removeObserver:self forKeyPath:@"contentOffset" context:Nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(UICollectionView *)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"contentOffset"] && object == self.collectionView ) {
        self.searchBar.frame = CGRectMake(self.searchBar.frame.origin.x,
                                          self.searchBarBoundsY + ((-1* object.contentOffset.y)-self.searchBarBoundsY),
                                          self.searchBar.frame.size.width,
                                          self.searchBar.frame.size.height);
    }
}


@end

可以通过检查将标题添加到情节提要中节标题在属性检查器下:

您还需要在集合视图数据源中实现以下方法:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    return view;
}

其中标识符也在故事板中设置为标题。

标题高度可以通过委托方法控制:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(0, 80);
}

故事板的外观如下:

当您手动添加搜索栏时,您可能无法获得正确的布局。搜索栏可以添加到故事板中。如果您选择在故事板中添加搜索栏,则必须重新构建视图(包括集合视图),以便它们包含在父视图中。否则,您必须手动操作约束才能获得搜索栏的正确位置。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在下面顶部的集合视图中添加部分标题 的相关文章

  • 是否可以使用 Firebase 安排推送通知? [复制]

    这个问题在这里已经有答案了 我已经阅读了我能找到的所有文档 但仍然不知道这是否可行 如果我是用户 我可以安排特定时间的推送通知吗 Example 1 我是用户并打开应用程序 2 我允许通知并转到 pickerView 或其他任何内容 并设置
  • 减少 CoreData 的调试输出?

    我正在开发一个使用 CoreData 的 iOS macOS 项目 它工作正常 但它会向控制台输出大量调试信息 这使得控制台无法使用 因为我的打印语句隐藏在所有与 CoreData 相关的内容中 我有一个非常简单的 CoreData 设置
  • AVAssetExportSession 为零 iPhone 7 - Plus 模拟器

    AVAssetExportSession在 iPhone 6 及以下版本上运行良好 但在 iPhone 7 iPhone 7 Plus 模拟器上运行不佳 Xcode 8 0 这段代码return nil在exportSession中 当在i
  • 在 iOS 中,如何创建一个始终位于所有其他视图控制器之上的按钮?

    无论是否呈现模态或用户执行任何类型的转场 有没有办法让按钮在整个应用程序中 始终位于顶部 而不是屏幕顶部 有什么方法可以让这个按钮可拖动并可捕捉到屏幕上吗 我正在以苹果自己的辅助触摸作为此类按钮的示例 您可以通过创建自己的子类来做到这一点U
  • Swift 中的 import 语句是否有相关成本?

    阅读字符串宣言 我看到一个段落 https github com apple swift blob master docs StringManifesto md batteries included关于避免Foundation不需要的时候导
  • 如何动态获取 UITableViewCell 的高度

    我创建了自定义的tableViewCell 我在UITableViewCell中添加了UIView SubView 所以我在 UIView 中的所有动态文本和图像内容都会根据文本和图像大小而变化 但现在 HeightforRowAtInde
  • 无法在 ios 应用程序中通过 googlecast 正确投射视频

    我正在开发一个基于 AVPlayer 的自定义视频播放器项目 尝试整合谷歌演员 我已经根据谷歌图进行了集成 https codelabs developers google com codelabs cast videos ios http
  • 如何使用 CNContacts 快速获取手机号码?

    我有一些代码可以检索用户联系人中的所有电话号码 但只想过滤掉手机号码 目前 我只是通过将第一个数字为 或第二个数字为 7 的数字添加到数组中来实现此目的 如下所示 func findContacts gt CNContact let key
  • SwiftUI 意外地自动弹出 NavigationLink

    我有一个简单的用例 其中一个屏幕使用 NavigationLink 推送另一个屏幕 iOS 14 5 有一个奇怪的行为 即推送的屏幕在被推送后立即弹出 Code NavigationLink destination EmptyView Em
  • BigQuery 未显示链接的 Firebase Analytics 事件日志的任何数据集

    我将我的帐户链接到 Big Query 但 Firebase Analytics 事件不会自动加载到 BigQuery 中 显示 未找到数据集 警告 我的工作进度附在下面 请查收 I have getting firebase Analyt
  • 如何在 iOS 13 中将 UISegmentedControl 的背景颜色设置为白色

    iOS 13 对 UISegmentedControl 进行了一些更改 包括切换所选片段时的非常漂亮的动画 但是我注意到它没有显示backgroundColor属性正确 它似乎总是有一点色彩 我见过回答如何设置的问题selectedSegm
  • 使用数组中的字符串淡入/淡出标签

    func setOverlayTitle self overlayLogo text Welcome var hello String Bon Jour GUTEN nMORGEN BONJOUR HOLA BUENOS D AS BUON
  • Swift:长按手势识别器 - 检测轻击和长按

    我想连接一个动作 如果手势是点击 它会以特定的方式为对象设置动画 但如果按下持续时间超过 0 5 秒 它会执行其他操作 现在 我刚刚连接了动画 我不知道如何区分长按和点击 如何访问新闻持续时间以实现上述目的 IBAction func ta
  • 未知异常和崩溃

    当我尝试快速滚动表格视图或从远程重新加载数据时 我的应用程序崩溃了 当我先进行远程获取然后滚动表格视图时 一切似乎都工作正常 我不知道下面的崩溃日志意味着什么 它只是有时工作正常 有时崩溃 Incident Identifier 710A1
  • 如何使用phonegap在iOS应用程序中防止键盘推送webview

    当屏幕底部的输入字段获得焦点时 键盘会向上推我的网络视图 并且页面的上部不再可见 我想防止键盘推高网络视图 有人有主意吗 对焦 设置window scrollTo 0 0 这可以防止键盘完全推高 webview input on focus
  • AVAudioPlayer 无法从网站播放 m4a 或 mp3 文件类型

    我试图在我的应用程序中找到一个仅纯 m4a 声音的 URL 我有音频的 URL 理论上可以下载它 然后 使用下载的文件URL到声音 我尝试使用AVAudioPlayer播放它 但它不播放任何声音 这是我的代码 在 URL 检索函数中 我调用
  • 当应用程序进入前台时,如何重新启动基于块的动画?

    我有以下基于块的动画 UIView animateWithDuration 0 5f delay 0 0f options UIViewAnimationOptionRepeat UIViewAnimationOptionAutorever
  • GLKit的GLKMatrix“列专业”如何?

    前提A 当谈论线性存储器中的 列主 矩阵时 列被一个接一个地指定 使得存储器中的前 4 个条目对应于矩阵中的第一列 另一方面 行主 矩阵被理解为依次指定行 以便内存中的前 4 个条目指定矩阵的第一行 A GLKMatrix4看起来像这样 u
  • Xcode 异步单元测试在主线程上等待

    我正在尝试使用 Xcode 中的单元测试来测试一些异步代码 但主线程被阻塞 问题在于 某些正在测试的代码期望从 iOS 类 AVFoundation 接收回调 但是 AVFoundation 类似乎只会在主线程上回调 问题是 如果我正在进行
  • 上传存档错误:“缺少 iOS 发行版签名身份......”

    我正在尝试使用 Xcode 将我的 iOS 应用程序存档上传到 iTunes Connect 但是当我单击 上传到 App Store 时 出现错误 Xcode 尝试查找或生成匹配的签名资产并 由于以下问题未能做到这一点 缺少 iOS 为

随机推荐

  • 如何在 SQL 中更新/插入指定日期范围内的随机日期

    请原谅我 我是一个绝对的新手 我需要 phpmyadmin 中这张表的帮助 我的表有以下列 Primary ID Begin Date End Date Timestamp 如何在 phpmyadmin 中更新具有指定日期范围 例如 一个月
  • 在 C++ 纯虚函数上应用“using”关键字

    B 类重写了 A 类的纯虚函数 print C 类继承了 B 类并具有 using A print 语句 那么为什么 C 类不是抽象类呢 class A public virtual void print 0 class B public
  • 仅在多索引中的第二个索引上使用 .loc

    我有多索引数据框 如下所示 value year name 1921 Ah 40 1921 Ai 90 1922 Ah 100 1922 Ai 7 其中year and name是指数 我想选择名称所在的每一行Ai出现 我努力了df loc
  • 通用 C++ 多维迭代器

    在我当前的项目中 我正在处理多维数据结构 底层文件按顺序存储 即一个巨大的数组 没有向量的向量 使用这些数据结构的算法需要知道各个维度的大小 我想知道是否已在某处以通用方式定义了多维迭代器类 以及是否有任何标准或首选方法来解决此问题 目前
  • 如何在 Kendo 菜单中检索 id 值

    我在我的项目中使用 Kendo 菜单 我想在单击所选项目时检索 id 值 我使用了 onSelect 事件 并且能够检索所选项目的文本 如何检索 id 值 您可以使用 HTML5 数据属性来完成此操作 HTML div class k co
  • python多处理池解释器中的断言错误

    我正在编写一个示例程序来测试 python 2 7 2 中工作线程多处理池的使用情况 这是我在 python ubuntu 解释器中编写的代码 gt gt gt from multiprocessing import Pool gt gt
  • Swift:guard let 和 where - 优先级

    有时 我想用guard结合let where简化我的代码 但我想知道 let 的优先级是什么以及在哪里 例如 class Person func check gt Bool print checking return nil func te
  • 无可用服务器时的 Serilog 和 seq

    当使用 Serilog 和 Seq 的应用程序找不到将日志发送到的服务器时 预期的行为是什么 每次尝试记录都会抛出异常吗 我希望我的应用程序使用 Seq 服务器 如果可用 但如果不可用 仍继续运行并记录到文件 当使用 Serilog 和 S
  • 为什么 Pry 不能在 Heroku 的控制台中运行?

    我的目标是使用 Pry 作为我的 Rails 应用程序的控制台 无论是在本地还是在我的临时服务器上 但我无法让它在 Heroku 上工作 我正在跟进these https github com pry pry wiki Setting up
  • 如何从 Xcode 项目中删除 cocoa pods 插件之一

    有人知道如何从 Xcode 项目中删除 cocoa pods 插件之一吗 例如我已经安装了afnetworking and nyximagekit在我的项目中 现在 我想删除nyximagekit但保留afnetwoking 怎么做 从 p
  • 为什么在 Fortran 中使用命令 PRINT 会覆盖输入文件?

    我正在编写代码并使用 Fortran 中的输入和输出功能 代码看起来像这样 仅用于简化 PROGRAM TEST REAL DIMENSION 1000 A REAL B INTEGER T Defining input and outpu
  • 获取文件系统限制

    我想编写一个函数来告诉我是否可以将文件 文件夹写入特定路径 我想这样做而不实际将任何文件写入磁盘 有 WINAPI 函数吗 感谢您的帮助 您可以使用获取文件安全性 http msdn microsoft com en us library
  • opencv rtsp流协议

    我想处理并显示从树莓派相机创建的网络 rtsp 流 我有这个代码 include
  • 我的项目中 SDL2 的链接器错误

    我使用 CMake 和 Code Blocks 从源代码构建 SDL2 并尝试将我自己的项目源链接到以下静态库 libSDL2 a libSDL2main a OpenGL32 lib 这三个库包含在称为 libdir 我使用批处理命令 我
  • 一个可定制的 diff 工具,可以生成报告(XML、HTML 格式)

    我想为非回归测试提供差异报告 我的程序是基于 Java 的 但我没有找到任何 API 来满足我的需求 因此 我使用外部工具 CSDiff 它接受 2 个文件作为参数并返回 HTML 报告 这很好而且很容易设置 现在我遇到的唯一问题是 HTM
  • iPhone——当 alpha 设置为零时,为什么 UIViews 上的 TouchBegan 不触发?

    是否正在进行一些优化以删除视图或其他内容 尽管我已经将其设置为透明 但我仍然希望它能够接收触摸事件 如果 alpha 0 这些事件似乎不会触发 你说得对 在透明视图上检测不到触摸 http developer apple com iphon
  • 1024px宽度的屏幕和1024px宽度的平板电脑是冲突的

    我正在使用 MediaQuery 创建响应式网站布局 如下所示 除了一个邪恶的问题外 一切正常 core css 默认应用于站点 它是桌 面版本的样式表 但正如您在此链接中看到的 当屏幕宽度为 1024px 或以下时 它将链接到 table
  • 无论页数如何,pyPdf 输出文件的大小都相同

    我正在尝试使用 pyPdf 将大型 pdf 中的几页提取到单独的文件中 每当我这样做时 生成的文件大小几乎与源文件相同 我认为这与文件内的书签有关 因为如果页面不包含任何链接 输出文件的大小会非常小 我不知道如何从输出文件中排除书签 fro
  • 如何用不同的颜色绘制填充路径/形状

    我需要为屏幕上的形状着色任何我想要的颜色 我目前正在尝试使用 UIImage 来做到这一点 我想根据我的愿望重新着色 据我所知 做到这一点的唯一方法是获取 UIImage 的各个像素 这需要我编写更多行代码来解决这个问题 除了我写的之外 还
  • 如何在下面顶部的集合视图中添加部分标题

    我正在使用带有搜索栏的集合视图 我通过 cod 添加了搜索栏 起始位置为 0 0 从顶部开始 所以现在我的图像看起来像这样 在此处输入图像描述 1 1 但我需要将标题转到我的搜索栏 我是通过故事板完成的 但是在运行时 我的标题名称和搜索栏具