[objective-c]更改基于中每个段标题分段控件的宽度?

标签: ios Objective-C
发布时间: 2016/10/2 17:28:43
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

这样,我喜欢的开始︰
Screenshot1.png

然后将添加一段,而发生这种情况︰
Screenshot2.png宽度是在 IB,不在代码中设置的。

我需要的只是一种方法来计算宽度对飞。最后,它会做这样的事情︰

control.width = (labelWidths + marginWidths);
// where marginWidths = (marginWidth * control.numberOfSegments)

解决方法 1:

Prgrmr 的答案中的方法在这里罚款其预期的目的,但这不是它的作品。

而不是添加不必要的开销与子视图 UILabel 自定义
我已经修改了上面的链接来与此中的示例代码︰

- (void)resizeSegmentsToFitTitles:(UISegmentedControl *)control {
    CGFloat textWidth = 0; // total width of all text labels
    CGFloat marginWidth = 0; // total width of all margins
    NSUInteger nSegments = control.subviews.count;
    UIView *aSegment = [control.subviews objectAtIndex:0];
    UIFont *theFont = nil;

    // get font for segment title label
    for (UILabel *label in aSegment.subviews) {
        if ([label isKindOfClass:[UILabel class]]) {
            theFont = label.font;
            break;
        }
    }

    // calculate width of text in each segment
    for (NSUInteger i = 0; i < nSegments; i++) {
        NSString *title = [control titleForSegmentAtIndex:i];
        CGFloat width = [title sizeWithFont:theFont].width;
        CGFloat margin = 15;

        if (width > 200) {
            NSString *ellipsis = @"…";
            CGFloat width2 = [ellipsis sizeWithFont:theFont].width;

            while (width > 200-width2) {
                title = [title substringToIndex:title.length-1];
                width = [title sizeWithFont:theFont].width;
            }

            title = [title stringByAppendingString:ellipsis];
        }

        [control setTitle:title forSegmentAtIndex:i];

        textWidth += width;
        marginWidth += margin;
    }

    // resize segments to accomodate text size, evenly split total margin width
    for (NSUInteger i = 0; i < nSegments; i++) {
        // size for label width plus an equal share of the space
        CGFloat textWidth = [[control titleForSegmentAtIndex:i]
                             sizeWithFont:theFont].width;
        // the control leaves a 1 pixel gap between segments if width
        // is not an integer value; roundf() fixes this
        CGFloat segWidth = roundf(textWidth + (marginWidth / nSegments));
        [control setWidth:segWidth forSegmentAtIndex:i];
    }

    // set control width
    [control setFrame:CGRectMake(0, 0, (textWidth + marginWidth), 30)];
}
赞助商