Tj3n
Tj3n

Reputation: 39

IOS drawing text inside a subview

im trying to draw a text on a subview, the view appearing fine but the text not, this is what im doing, the view have black color, the text have white color, text and rect value given in other method:

NSString* sumText = [[NSString alloc]initWithFormat:@"%0.1f",sum];
CGRect textRect = CGRectMake(chartLocation.x+chartLength+10,
                              chartLocation.y,
                              20,
                              20);
[self drawTextRect:sumText inRect:textRect];


-(void)drawTextRect:(NSString *)sumText inRect:(CGRect)textRect {
UIFont* font=[UIFont fontWithName:@"Arial" size:(20/2)];
UIColor* textColor = [UIColor whiteColor];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle]mutableCopy];
paragraphStyle.alignment = NSTextAlignmentCenter;
NSDictionary* stringAttr=@{NSFontAttributeName:font,NSForegroundColorAttributeName:textColor,NSParagraphStyleAttributeName:paragraphStyle};
UIView* textView =[[UIView alloc] initWithFrame:textRect];
textView.backgroundColor = [UIColor blackColor];

[sumText drawInRect:textRect withAttributes:stringAttr];
[self.view addSubview:textView];}

am i do anything wrong? thanks

Upvotes: 0

Views: 430

Answers (2)

Morten Fast
Morten Fast

Reputation: 6320

The drawInRect:withAttributes: method draws the string in the current graphics context. You have not defined a context, so your drawing goes nowhere.

If you want to draw the string yourself, you should subclass UIView, add the required properties (sumText), and overwrite drawRect:. A graphics context is automatically created for you in drawRect: so you can just go ahead and draw.

But really, you probably just want to use a UILabel instead.

Upvotes: 1

Jatin Patel - JP
Jatin Patel - JP

Reputation: 3733

there is another way you can achieve what you want .

UILabel* lblText = [[UILabel alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];
lblText.text = @"Hello World!";
lblText.backgroundColor = [UIColor blackColor];
lblText.textColor = [UIColor whiteColor];
[self.view addSubview:lblText];

And Output is:

Output

Upvotes: 0

Related Questions