2017-06-08 5 views
0

同じ1行のテキストがboundingRectWithSize and CoreTextメソッドの間で異なる幅になります。ここで iOS boundingRectWithSizeとCoreTextメソッドの間のテキストサイズの計算に関する別の結果

は私のコードとの結果である:

- (IBAction)buttonSeletor:(id)sender { 
    [self getSeparatedLinesWithText:self.contentField.text fontSize:self.fontField.text.floatValue labelWidth:10000]; 
} 

- (void)getSeparatedLinesWithText:(NSString *)text fontSize:(CGFloat)fontSize labelWidth:(CGFloat)labelWidth 
{ 
    UIFont *font = [UIFont systemFontOfSize:fontSize]; 
    CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL); 
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text]; 
    CTParagraphStyleSetting set[kCTParagraphStyleSpecifierCount] = { 0 }; 
    int count = 0; 
    CTLineBreakMode paraLineBreak = (CTLineBreakMode)NSLineBreakByCharWrapping; 
    set[count].spec = kCTParagraphStyleSpecifierLineBreakMode; 
    set[count].valueSize = sizeof(CTLineBreakMode); 
    set[count].value = &paraLineBreak; 
    count++; 
    CTParagraphStyleRef style = CTParagraphStyleCreate(set, count); 

    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)]; 
    [attStr addAttribute:(NSString *)kCTParagraphStyleAttributeName value:(__bridge id)style range:NSMakeRange(0, attStr.length)]; 
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr); 
    CGMutablePathRef path = CGPathCreateMutable(); 
    CGPathAddRect(path, NULL, CGRectMake(0,0,labelWidth,100000)); 
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL); 
    NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame); 

    CGFloat width = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName :font} context:nil].size.width; 
    CTLineRef obj = (__bridge CTLineRef)(lines[0]); 
    CGRect r = CTLineGetBoundsWithOptions(obj, kCTLineBoundsExcludeTypographicLeading); 
    NSLog(@"\ntext %@\nboundingRectWithSize %f\nCoreText %f\nboundingRectWithSize/CoreText %f",text,width,r.size.width,width/r.size.width); 
} 

結果:

Result

デザインスケッチ:あなたは最大3行を表示したい場合は

Design sketch

+0

達成したいことはありますか? – Lion

+0

テキストが長い場合、3行だけが表示されます.Ultabel –

+0

のCoreTextを使用すると、3行の内容が同じ長さではなく、3行の長さになります。テキストを表示するのに何を使用していますか?私はユーラベルを意味する? – Lion

答えて

0

あなたはtを必要としないラベルo幅などを計算する。あなたはあなたのインターフェース(ストーリーボードまたはxib)からそれをautolayoutで管理することができます。

ラベルには、のような3つの制約があり、行番号は3に設定されています。もしあなたが固定幅のラベルを持っていたら、top,leading, fixed widthのような制約を設定し、行の数は3でなければなりません!

コンテンツに応じてサイズが変更され、3行以上は表示されません。

+0

テキスト行が3より大きい場合、3行目の最後の部分を傍受して追加する必要もあります...すべて表示 –

+0

"... show"はUIButtonですので、3行目の幅を知る必要があります。 –

+0

[TTTAttributedLabel](https://github.com/TTTAttributedLabel/TTTAttributedLabel)をご覧ください。 – Lion

関連する問題