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

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(使用前将#替换为@)

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

随机推荐

  • 如何在 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 但我需要将标题转到我的搜索栏 我是通过故事板完成的 但是在运行时 我的标题名称和搜索栏具