2010-11-04 88 views
12

有沒有辦法讓文字中的可見部分被包裹起來UILabel?我的意思是最後一個可見的角色?UILabel文字的可見部分

我想製作兩個標籤四捨五入的圖像,並希望繼續爲第二個標籤上的第一個標籤不正確的文本。

我知道[NSString sizeWithFont...]但有沒有像[NSString stringVisibleInRect: withFont:...]顛倒的東西? :-)

預先感謝您。

回答

7

你可以使用一個類來擴展的NSString和創建方法你提到

@interface NSString (visibleText) 

- (NSString*)stringVisibleInRect:(CGRect)rect withFont:(UIFont*)font; 

@end 

@implementation NSString (visibleText) 

- (NSString*)stringVisibleInRect:(CGRect)rect withFont:(UIFont*)font 
{ 
    NSString *visibleString = @""; 
    for (int i = 1; i <= self.length; i++) 
    { 
     NSString *testString = [self substringToIndex:i]; 
     CGSize stringSize = [testString sizeWithFont:font]; 
     if (stringSize.height > rect.size.height || stringSize.width > rect.size.width) 
      break; 

     visibleString = testString; 
    } 
    return visibleString; 
} 

@end 
+1

嗨!謝啦。但在我看來,這種循環方法太重了。我想找一些本地的東西。 – Evgeny 2010-11-07 16:50:07

+0

我不知道有一種方法可以在本地執行此操作。除非你將這個代碼稱爲鉅額,否則我不會想象它會對你的應用產生任何負面影響。如果您真的擔心內存使用情況,可以查看alloc並釋放所有字符串實例。 – Vertism 2010-11-08 15:33:32

+1

我不擔心內存,只是處理器負載。看起來sizeWithFont應該很沉重,我想知道有沒有辦法獲得,例如,UILabel事件,當它剪掉一些文本...這是我的問題是關於:-)但在我看來,那裏是無法解決的。唯一的辦法就是你的。 – Evgeny 2010-11-08 18:37:11

0

這裏有一個O(log n)的與iOS 7的API方法。只有表面測試,請評論,如果你發現任何錯誤。

- (NSRange)hp_visibleRange 
{ 
    NSString *text = self.text; 
    NSRange visibleRange = NSMakeRange(NSNotFound, 0); 
    const NSInteger max = text.length - 1; 
    if (max >= 0) 
    { 
     NSInteger next = max; 
     const CGSize labelSize = self.bounds.size; 
     const CGSize maxSize = CGSizeMake(labelSize.width, CGFLOAT_MAX); 
     NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; 
     paragraphStyle.lineBreakMode = self.lineBreakMode; 
     NSDictionary * attributes = @{NSFontAttributeName:self.font, NSParagraphStyleAttributeName:paragraphStyle}; 
     NSInteger right; 
     NSInteger best = 0; 
     do 
     { 
      right = next; 
      NSRange range = NSMakeRange(0, right + 1); 
      NSString *substring = [text substringWithRange:range]; 
      CGSize textSize = [substring boundingRectWithSize:maxSize 
                 options:NSStringDrawingUsesLineFragmentOrigin 
                attributes:attributes 
                 context:nil].size; 
      if (textSize.width <= labelSize.width && textSize.height <= labelSize.height) 
      { 
       visibleRange = range; 
       best = right; 
       next = right + (max - right)/2; 
      } else if (right > 0) 
      { 
       next = right - (right - best)/2; 
      } 
     } while (next != right); 
    } 
    return visibleRange; 
} 
+0

我想我擊敗了O(1)擊中CoreText:http://stackoverflow.com/a/25899300/860000 – 2014-09-17 20:34:47