IOS在子视图中绘制文本

时间:2015-04-10 04:39:12

标签: ios objective-c

我试图在子视图上绘制文本,视图显得很好而文本没有,这就是我在做什么,视图有黑色,文本有白色,文本和其他方法给出的rect值: / p>

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];}
我做错了什么?感谢

2 个答案:

答案 0 :(得分:1)

drawInRect:withAttributes:方法在当前图形上下文中绘制字符串。您尚未定义上下文,因此您的绘图无处可去。

如果您想自己绘制字符串,则应该继承UIView,添加必需的属性(sumText),并覆盖drawRect:。在drawRect:中自动为您创建图形上下文,以便您可以继续绘制。

但实际上,您可能只想使用UILabel代替。

答案 1 :(得分:0)

还有另一种方法可以达到你想要的效果。

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];

输出是:

Output