我认为使用公共 API 直接从 UISearchBar 访问 UISegmentedControl 的属性(范围栏)是不可能的。
解决此问题的一种方法是访问UISegmentedControl 是使用UISearchBar 的私有属性:_scopeBar。
这样做的一种简洁方法是在UISearchBar 上声明一个类别以公开此属性:
@interface UISearchBar (ExposeScopeBar)
@property (readonly) UISegmentedControl *_scopeBar;
@end
那么你所要做的就是访问范围栏(这是一个经典的UISegmentedControl),并将其apportionsSegmentWidthsByContent属性设置为true:
self.searchBar._scopeBar.apportionsSegmentWidthsByContent = YES;
如果您需要对段大小进行更细粒度的控制,也可以使用UISegmentedControl 的-setWidth:forSegmentAtIndex: 方法。
请记住,尽管这使用了私有 UIKit API,并且您的应用会被 App Store 拒绝。
另一种选择是在UISearchBar 视图层次结构中递归搜索UISegmentedControl,而不是使用私有属性。
这里有一个伪代码 sn-p 来做到这一点:
- (UISegmentedControl *)scopeBarForSearchBar:(UISearchBar *)searchBar
{
return [self scopeBarInViewHierarchy:searchBar];
}
- (UISegmentedControl *)scopeBarInViewHierarchy:(UIView *)view
{
if ([view isKindOfClass:[UISegmentedControl class]])
{
return view;
}
for (UIView *child in [view subviews])
{
UIView *result = [self scopeBarInViewHierarchy:child];
if (result)
{
return result;
}
}
return nil;
}
再说一遍:这是伪代码。未经测试。
此解决方案不使用私有 API,因此它应该毫无问题地通过 App Store 验证。