如何在Xcode中调整search bar的scope titles字体大小以适配iPad?
解决UISearchBar Scope Titles 在iPad上字体过小的问题
这个问题我之前也碰到过,确实Storyboard里找不到直接调整scope titles字体的选项——因为SearchBar的scope bar本质是个隐藏的UISegmentedControl,系统没在界面编辑器里暴露它的字体设置。不过用代码处理起来很简单,给你两个实用的方案:
方案1:全局统一设置(适合整个应用的SearchBar都需要适配)
如果希望所有SearchBar的scope titles在iPad上都用更大的字体,可以用UIAppearance来全局配置,这样不用逐个修改SearchBar:
Swift 代码
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 针对iPad设备单独设置 if UIDevice.current.userInterfaceIdiom == .pad { UISegmentedControl.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16) // 这里替换成你需要的字体大小 ], for: .normal) } return true }
Objective-C 代码
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { [[UISegmentedControl appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitleTextAttributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:16] } forState:UIControlStateNormal]; } return YES; }
方案2:针对单个SearchBar设置(只修改特定的SearchBar)
如果只想调整某一个SearchBar的scope titles字体,可以直接获取它内部的UISegmentedControl来修改:
Swift 代码
override func viewDidLoad() { super.viewDidLoad() // 假设你的SearchBar实例名为searchBar if let scopeBar = searchBar.scopeBar as? UISegmentedControl, UIDevice.current.userInterfaceIdiom == .pad { scopeBar.setTitleTextAttributes([ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16) ], for: .normal) } }
Objective-C 代码
- (void)viewDidLoad { [super viewDidLoad]; // 假设你的SearchBar实例名为searchBar if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { UISegmentedControl *scopeBar = (UISegmentedControl *)self.searchBar.scopeBar; [scopeBar setTitleTextAttributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:16] } forState:UIControlStateNormal]; } }
这两个方案都很简便,你可以根据自己的需求选一个。测试的时候记得切换到iPad模拟器或者真机看看效果,字体大小可以根据你的UI设计调整~
内容的提问来源于stack exchange,提问作者itch
相关产品推荐
相关产品推荐

