2011-11-04 142 views
3

我有以下代碼用CoreText格式化一段文本。段落與CoreText對齊

(...) 

CTFontRef fontRef = CTFontCreateWithName((CFStringRef)fontName, 
             [self.fontSize floatValue], NULL); 

CTTextAlignment alignment = kCTJustifiedTextAlignment; 

CTParagraphStyleSetting settings[]={ 
    {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment}, 
}; 

CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, 
              sizeof(settings)/sizeof(settings[0])); 

self.attrs = [NSDictionary dictionaryWithObjectsAndKeys: 
     //The following line doesn't work! 
     (id)paragraphStyle, kCTParagraphStyleAttributeName, 
     (id)self.color.CGColor, kCTForegroundColorAttributeName, 
     (id)fontRef, kCTFontAttributeName, 
     nil]; 

CFRelease(fontRef); 
CFRelease(paragraphStyle); 

NSMutableAttributedString* aString = [[[NSMutableAttributedString alloc] initWithString:@""] autorelease]; 

(...) 

[aString appendAttributedString:[[[NSAttributedString alloc] initWithString:text attributes:attrs] autorelease]]; 

如果我刪除以下屬性對(值/鍵),一切正常(顏色,字體等)。

(id)paragraphStyle, (NSString*)kCTParagraphStyleAttributeName, 

如果我把ATTRS字典此屬性,程序上,當我使用CTFrameGetVisibleStringRange一個無限循環進入。

我在做什麼錯了?


UPDATE:馬蒂亞斯答案後,我想通了,該代碼是沒有問題的。在文本中間丟失了一些HTML標籤(垃圾),出於某種原因,FrameSetter正在消失,返回並返回空的範圍。當文字上沒有HTML標籤時,一切都很順利。

回答

3

我懷疑CTParagraphStyleCreate返回NULL由於某種原因導致dictionaryWithObjectsAndKeys:創建一個空的字典。但是我看不到您的段落樣式設置有任何錯誤。

看看我的CoreTextLabel.m使用段落樣式設置的類源代碼。

+0

謝謝,我會看到你的代碼。我把一個斷點和'CTParagraphStyleCreate'返回一個值,而不是NULL。 – javsmo

+0

我剛剛注意到,當我啓用該行時,'CTFrameGetVisibleStringRange'返回'CTFrame:visible string range =(14058,0)'。這是一個空的範圍,因爲長度== 0.這導致無限循環,因爲我將frame.length添加到textPosition以處理可見列。 – javsmo

+0

嗯好的。你能否讓你的例子更完整? –