2013-10-09 17 views
28

我正在研究我的應用程序的新版本,並試圖替換棄用的消息,但無法通過這一個。drawInRect:withAttributes vs drawInRect:withFont:lineBreakMode:alignment

我想不通爲什麼drawInRect:withAttributes不起作用。當發送drawInRect:withFont:lineBreakMode:alignment消息時代碼正確顯示,但在發送drawInRect:withAttributes時不起作用。

我使用相同的矩形和字體,我相信是相同的文字樣式。常量只是將rect定位在圖像下面,但是我對兩個調用都使用相同的矩形,所以我確定矩形是正確的。

(注意,下面使用bs.name是一個NSString對象)使用變量

 CGRect textRect = CGRectMake(fCol*kRVCiPadAlbumColumnWidth, 
            kRVCiPadAlbumColumnWidth-kRVCiPadTextLabelYOffset, 
            kRVCiPadAlbumColumnWidth, 
            kRVCiPadTextLabelHeight); 
     NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy]; 
     textStyle.lineBreakMode = NSLineBreakByWordWrapping; 
     textStyle.alignment = NSTextAlignmentCenter; 
     UIFont *textFont = [UIFont systemFontOfSize:16]; 

這不工作(沒有什麼是在屏幕上繪製)從上面

 [bs.name drawInRect:textRect 
      withAttributes:@{NSFontAttributeName:textFont, 
           NSParagraphStyleAttributeName:textStyle}]; 

這個工作(字符串在屏幕上正確繪製)使用上面的相同變量

 [bs.name drawInRect:textRect 
        withFont:textFont 
       lineBreakMode:NSLineBreakByWordWrapping 
        alignment:NSTextAlignmentCenter]; 

任何協助將是偉大的。謝謝。

+0

你是說'drawInRect:withAttributes:'不起作用是什麼意思? –

+0

非常好的問題。對不起,我沒有詳細說明。包含在bs.name中的字符串使用drawInRect在屏幕上正確繪製:withFont:lineBreakMode:alignment消息,但在使用drawInRect:withAttributes消息時不顯示(不繪製任何東西)。 –

回答

28

我已經和drawRect:一個UIView僅包含您所提供

- (void)drawRect:(CGRect)frame 
{ 
    NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy]; 
    textStyle.lineBreakMode = NSLineBreakByWordWrapping; 
    textStyle.alignment = NSTextAlignmentCenter; 
    UIFont *textFont = [UIFont systemFontOfSize:16]; 

    NSString *text = @"Lorem ipsum"; 

    // iOS 7 way 
    [text drawInRect:frame withAttributes:@{NSFontAttributeName:textFont, NSParagraphStyleAttributeName:textStyle}]; 

    // pre iOS 7 way 
    CGFloat margin = 16; 
    CGRect bottomFrame = CGRectMake(0, margin, frame.size.width, frame.size.height - margin); 
    [text drawInRect:bottomFrame withFont:textFont lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter]; 
} 

我看不出這兩種方法的輸出之間有什麼區別的代碼。也許問題在你的代碼中的其他地方?

+0

感謝您提供此答案的工作。我的代碼也是從UIView上的drawRect:執行的。我同意它必須在別的地方,但如果我評論一個或另一個,一個工作,另一個不工作。也許矩形需要重新計算,無論出於何種原因,在iOS 7上不同(僅供參考,iOS 7的方式是drawInRect:withAttributes)。我會更多地討論矩形。再次感謝。 –

+0

確保'CGRect'傳遞給兩個方法是一樣的。您還可以嘗試1)更改文本顏色,2)在矩形上繪製背景,以確保它位於您想要的位置。這些步驟相當簡單,但也許他們會幫助找出問題所在。 –

+0

我使用完全相同的方法完全相同的代碼(不是兩種方法)。如果用完全相同的矩形代替drawRect:(old)與drawRect:(new)在代碼中完全相同的位置,則其中一個工作,一個不工作。我仍然難倒。如果我找到任何東西,我會發布。 –

36

要設置文本的顏色,您需要傳遞屬性中的NSForegroundColorAttributeName作爲附加參數。

NSDictionary *dictionary = @{ NSFontAttributeName: self.font, 
           NSParagraphStyleAttributeName: paragraphStyle, 
           NSForegroundColorAttributeName: self.textColor}; 
相關問題