【问题标题】:How do I set different widths on scope buttons in UISearchBar?如何在 UISearchBar 的范围按钮上设置不同的宽度?
【发布时间】:2014-10-07 22:10:52
【问题描述】:

我有一个小问题,还没有找到任何解决方案。

我的应用程序中有一个UISearchBar 和一个ScopeBarScopeBar 包括 4 个范围按钮。目前它们都具有相同的宽度。

我的一个按钮的文本比其他按钮长。就我而言,文本被截断。它看起来像:

[  short  |  short  |longte...|  short  ]

如果我可以最小化短按钮的宽度并为第三个按钮添加一些像素,那么显示整个文本不会有问题。

第一个问题: 是否可以设置不同的按钮大小?

第二个: 如果是,我该怎么做?

【问题讨论】:

    标签: ios objective-c uisearchbar uisegmentedcontrol


    【解决方案1】:

    我认为使用公共 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 验证。

    【讨论】:

    • 非常感谢。我尝试了第二个,因为我的应用程序始终可用很重要。我不得不改变一些东西:(UIView *child in [view subviews])。也许你可以编辑你的答案并纠正这个?其次,方法 appportionsSegmentWidthsByContent 在我的情况下不起作用。我必须为这些段赋予固定值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多