本文介绍了根据每个分段中的标题更改分段控件的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我喜欢这样开始:
Starts like this, which I like:
但是随后我添加了一个细分,并且发生了这种情况: 宽度是在IB中设置的,而不是在代码中设置的.
But then I add a segment and this happens: The width is set in IB, not in code.
我需要的是一种动态计算宽度的方法.最后,它将执行以下操作:
All I need is a method to calculate width on the fly. At the end, it would do something like this:
control.width = (labelWidths + marginWidths); // where marginWidths = (marginWidth * control.numberOfSegments)推荐答案
prgrmr的答案此处中的方法适用于它的预期目的,但事实并非如此.
The method in prgrmr's answer here works fine for its intended purpose, but this is not it.
与其通过自定义UILabel子视图添加不必要的开销, 我已经修改了上面链接中的示例代码来解决这个问题:
Rather than adding unnecessary overhead with custom UILabel subviews, I've modified the example code in the above link to come up with this:
- (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)]; }更多推荐
根据每个分段中的标题更改分段控件的宽度?
发布评论