我正在维护一个主要用Objective-C编写的大型iPad应用程序,它在几个iOS版本中幸存下来.我遇到了这样的情况:我需要在iOS 11之前的标签栏中出现几个标签栏(在标题上方而不是旁边有图标).我的解决方案是创建一个UITabBar的子类,覆盖traitCollection
方法,以便它总是返回一个水平紧凑的trait集合.这会导致iOS 11在所有选项卡栏按钮的图标下方显示标题.
为了使用它,将故事板中选项卡栏的自定义类设置为这个新的子类,并将代码中指向选项卡栏的任何出口更改为这个新类型(不要忘记导入下面的头文件).
这个在这种情况下,h文件几乎是空的:
//
// MyTabBar.h
//
#import <UIKit/UIKit.h>
@interface MyTabBar : UITabBar
@end
这是答案.使用traitCollection
方法实现的m文件:
//
// MyTabBar.m
//
#import "MyTabBar.h"
@implementation MyTabBar
// In iOS 11, UITabBarItem's have the title to the right of the icon in horizontally regular environments
// (i.e. the iPad). In order to keep the title below the icon, it was necessary to subclass UITabBar and override
// traitCollection to make it horizontally compact.
- (UITraitCollection *)traitCollection {
return [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassCompact];
}
@end