有什么方法可以使 UISegmentedControl 中的段宽度与内容成正比?

Is there any way to get the width of the segments in a UISegmentedControl that is proportional to content?

UISegmentedControl 中的片段与内容成正比的情况下 widthForSegmentAtIndexviewDidLayoutSubviews 调用时似乎 return 0。无论如何要获得实际宽度? (我正在使用自动布局。)

如果没有,有什么办法可以得到一个segment对应的subview吗? segmentedControl.subviews[index] 工作不可靠。

如果没有办法做到这一点,是否可以使用 UISegmentedControl 的替代方法?

谢谢!

根据我的测试,无论每个单独的段的文本大小如何,段的宽度似乎总是相等的。

CGFloat segmentWidth = segmentedControl.frame.size.width / segmentedControl.numberOfSegments;

编辑

不幸的是,如果 segmentedControl 正在使用 apportionsSegmentWidthsByContent,上述答案将不起作用。在那种情况下,我找不到一种简单的方法来获取段的宽度。

但是,您可以手动获取您感兴趣的片段的文本,然后计算它 'should' 的长度(取决于您想要两边的填充量),然后使用该数字并使用 setWidth:forSegmentAtIndex: 方法将段设置为计算出的宽度,然后您就可以确定段的宽度了。

以下类别使 NSSegmentedControl 能够告诉您其计算的段宽度。它并不完美-请参阅评论中的免责声明。

@implementation NSSegmentedControl (SegmentedControlWidthComputation)
/* Note: This implementation doesn't properly handle cells with images. It also makes some guesses about AppKit's behavior, and should be treated as an estimation rather than an exact value. */
- (CGFloat)computedWidthForSegment:(NSInteger)SEGIDX
{
    CGFloat pad = 0;
    switch (self.controlSize) {
        case (NSControlSizeMini): pad = 16; break;
        case (NSControlSizeSmall): pad = 22; break;
        case (NSControlSizeRegular): pad = 28; break;
    }

    return [[NSAttributedString alloc] initWithString:[self labelForSegment:SEGIDX] attributes:@{NSFontAttributeName:self.font}].size.width + pad;
}
@end