2012-08-16 45 views
5

開始這樣的,我喜歡:
Screenshot1.png根據每個片段中的標題更改分段控件的寬度?

但我添加一個段和發生這種情況:
Screenshot2.png 寬度在IB設定,而不是在代碼。

我所需要的只是一種在飛行中計算寬度的方法。最後,它會做這樣的事情:

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

回答

7

在prgrmr的回答方法here工作正常,其預期目的,但這不是它。

而不是增加自定義的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)]; 
} 
+0

我在ios7以此來糾正分段控制截斷的標題,當它不應該,不過最後一段不tapable ......任何IDEEA爲什麼有問題? – user1028028 2013-09-20 08:03:55

+0

http://stackoverflow.com/questions/18890428/uisegmentedcontrol-truncates-segment-titles – user1028028 2013-09-20 08:04:58

+0

[這裏](http://stackoverflow.com/a/23492688/2254935)被簡化和iOS 7友好版本。 – 2014-05-06 11:03:20

18

您可以使用屬性apportionsSegmentWidthsByContent並將其設置爲YES

+0

當我以編程方式更改文本時,這似乎不適用於我。 – primehalo 2016-02-29 18:29:07

+1

@primehalo每次以編程方式更新文本後,請嘗試設置此屬性。 – Rajesh 2016-03-03 11:26:10

+0

感謝@Rajesh快速修復! – 2017-03-29 20:29:27

4

如下圖所示,將Auto-Size屬性更改爲「與內容成比例」。

enter image description here

+0

這應該是被接受的答案 - 它是最快,最簡單並且效果很好的。謝謝你,Ankit。 – 2017-05-31 05:49:48