我能够实现这个简单的例子
![screenshot](https://i.stack.imgur.com/kVuZJ.png)
by using a subclass of UINavigationBar and setting a collection view to the view controller's navigationItem.titleView
#import <UIKit/UIKit.h>
@interface NavigationBar : UINavigationBar
@end
#import "NavigationBar.h"
@implementation NavigationBar
- (CGSize)sizeThatFits:(CGSize)size
{
return CGSizeMake(self.superview.bounds.size.width, 80);
}
-(void)setFrame:(CGRect)frame {
CGRect f = frame;
f.size.height = 80;
[super setFrame:f];
}
@end
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
#import "ViewController.h"
#import "CollectionViewCell.h"
@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, weak) UICollectionView *collectionView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 300, 80) collectionViewLayout:layout];
collectionView.backgroundColor = [UIColor clearColor];
self.navigationItem.titleView = collectionView;
[collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
collectionView.delegate = self;
collectionView.dataSource = self;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 5;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor orangeColor];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(50, 50);
}
@end
我在界面生成器中设置了自定义导航栏
![screenshot](https://i.stack.imgur.com/oprql.png)
免责声明1:我不能保证这是一个面向未来的解决方案或在任何情况下都有效。我没有用自动布局或旋转之类的东西来测试它。
免责声明2:我个人会独立于视图控制器实现任何数据源/委托。对于表视图和集合视图,我使用我自己生长的OFAPopulator.
这是一个示例代码:gitlab.com/vikingosegundo/collectionview-in-navigationbar/tree/... 其中仍然有一些 UI 怪癖。但这或许是意料之中的。我猜苹果只是没有考虑我们改变高度。实际上,我从未见过导航栏具有不同高度的应用程序。但代码回答了你的问题。给予它更多的爱,它可能对你有用。