2014-04-14 49 views
0

我现在感觉非常愚蠢。iOS如何在UIViewController中绘制文字

我想绘制文本到UIViewController。

我使用的Xcode 5,并开始与一个简单的单页的项目,并没有做什么别的,只是加入这个代码到ViewController.m:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    CGRect myRect=CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height); 
    UIFont *myFont=[UIFont fontWithName:@"Helvetica" size:50]; 

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; 
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; 
    paragraphStyle.alignment = NSTextAlignmentRight; 

    NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init]; 
    [attributes setObject:myFont forKey:NSFontAttributeName]; 
    [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName]; 
    [attributes setObject:[NSNumber numberWithFloat:4] forKey:NSStrokeWidthAttributeName]; 
    [attributes setObject:[UIColor whiteColor] forKey:NSStrokeColorAttributeName]; 
    [@"test" drawInRect:myRect withAttributes:attributes]; 

    // draw fill 
    [attributes removeObjectForKey:NSStrokeWidthAttributeName]; 
    [attributes removeObjectForKey:NSStrokeColorAttributeName]; 
    [attributes setObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName]; 
    [@"test" drawInRect:myRect withAttributes:attributes]; 
} 

它运行没有错误,但不会产生任何的文字 - 为什么?

+0

你只是在做这个练习来学习(如果是的话,对你有好处)?否则,你可以在视图中放一个'UILabel',让它处理你的文字。 –

+0

是的,试图学习 - 我已经遇到了UILabels将字体下降到字体上的麻烦,所以我想我会看看是否可以自己绘制文本并消除问题。 – wayneh

回答

0

drawInRect方法不能与UIViewController工作。该方法是一种UIView方法,并且只有在您的课程是UIView课程或子类时才有效。

因此,正如上面提到的,你可以设置一个UILabel的文本属性和你喜欢的地方在屏幕上显示出来。它应该给你同样的效果。或者,您可以尝试将子类更改为UIView,但这可能需要对代码进行更多修改。

+0

所以,如果我想在我的UIViewController中使用自动创建的视图,它会工作吗?如果是这样,我将如何在视图中使用Rect?或者我可以添加一个ImageView? – wayneh

+0

我没有运用自动创建的视图,如'self.view',或'UIImageView'与'drawInRect'方法。你可以在Core Graphics上使用'UIImageView'进行绘制,但是这可能不是你用绘图文本寻找的东西。 – tfrank377

0

为了增加tfrank377,你可以像

UILabel *addLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)]; 
    [self.view addSubview:addLabel]; 
    addLabel.text = @"Hello World"; 

,这将显示在您的UIView文本编程方式添加标签。

+0

谢谢,但由于上述其他错误,我正在尝试除UILabels之外的其他内容。 – wayneh

+0

你能否举一个下行者被切断的例子吗? – flooie

+0

当然 - 这是我问过的另一个问题。请注意,关键是不要缩小字体,直到问题消失 - 重点是显示可能的最大字体... http://stackoverflow.com/questions/22897158/fonts-not-fitting-properly-in-的UILabel-伸或 - 伸裁剪 – wayneh