2011-05-02 10 views
5

मैं केंद्र संरेखण के साथ कोको एनएसवी व्यू में नई लाइनों (\ n) के साथ एक स्ट्रिंग खींचने की कोशिश कर रहा हूं। उदाहरण के लिए अगर मेरे स्ट्रिंग है:कोको में केंद्र संरेखण के साथ टेक्स्ट ड्रा

NSString * str = @"this is a long line \n and \n this is also a long line"; 

मैं इस चाहते हैं कुछ हद तक प्रकट करने के लिए के रूप में:

this is a long line 
     and 
this is also a long line 

यहाँ NSView drawRect विधि अंदर मेरे कोड है:

NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; 

[paragraphStyle setAlignment:NSCenterTextAlignment]; 

NSDictionary * attributes = [NSDictionary dictionaryWithObject:paragraphStyle forKey:NSParagraphStyleAttributeName]; 

NSString * mystr = @"this is a long line \n and \n this is also a long line"; 

[mystr drawAtPoint:NSMakePoint(20, 20) withAttributes:attributes]; 

यह अभी भी ड्रॉ बाएं संरेखण के साथ पाठ। इस कोड के साथ क्या समस्या है?

उत्तर

13

-[NSString drawAtPoint:withAttributes:] राज्यों निम्नलिखित के लिए दस्तावेज़: प्रतिपादन क्षेत्र के

चौड़ाई (ऊर्ध्वाधर लेआउट के लिए ऊंचाई) drawInRect:withAttributes: है, जो एक सीमांकन आयत का उपयोग करता है के विपरीत असीमित है,। नतीजतन, यह विधि टेक्स्ट को एक पंक्ति में प्रस्तुत करती है।

चूंकि चौड़ाई असीमित है, इसलिए यह विधि पैराग्राफ संरेखण को छोड़ देती है और हमेशा स्ट्रिंग बाएं-गठबंधन को प्रस्तुत करती है।

आपको इसके बजाय -[NSString drawInRect:withAttributes:] का उपयोग करना चाहिए। चूंकि यह एक फ्रेम स्वीकार करता है और फ्रेम की चौड़ाई होती है, यह केंद्र संरेखण की गणना कर सकती है।

NSMutableParagraphStyle * paragraphStyle = 
    [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease]; 
[paragraphStyle setAlignment:NSCenterTextAlignment]; 
NSDictionary * attributes = [NSDictionary dictionaryWithObject:paragraphStyle 
    forKey:NSParagraphStyleAttributeName]; 

NSString * mystr = @"this is a long line \n and \n this is also a long line";  
NSRect strFrame = { { 20, 20 }, { 200, 200 } }; 

[mystr drawInRect:strFrame withAttributes:attributes]; 

ध्यान दें कि आप अपने मूल कोड में paragraphStyle लीक कर रहे हैं: उदाहरण के लिए।

+0

क्या मैं अभी भी कचरा संग्रह का उपयोग कर रहा था अगर मैं पैराग्राफ स्टाइल लीक करूँगा? – AmaltasCoder

+1

@Amal यदि आप कचरा संग्रह का उपयोग कर रहे हैं, तो कोई रिसाव नहीं है। –

संबंधित मुद्दे