drawAtPoint不会在视图中呈现文本

时间:2013-11-02 12:53:57

标签: ios objective-c nsstring ios7

我正在尝试使用drawAtPoint:point withAttributes:attrs方法向视图追加一个字符串,但是在视图内的任何地方都看不到字符串,或者至少我看不到它(可能是那个颜色与视图相同,白色。

以下代码是我在视图控制器的viewDidLoad中使用的代码:

NSMutableDictionary *stringAttributes = [[NSMutableDictionary alloc] init];


[stringAttributes setObject:[UIColor redColor]forKey: NSForegroundColorAttributeName];


NSString *someString = [NSString stringWithFormat:@"%@", @"S"];

[someString drawAtPoint:CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2) withAttributes: stringAttributes];

我做错了什么?

编辑:按照@ rokjarc的建议,我创建了一个带有drawRect方法的视图控制器,将该字符串添加到当前上下文中:

#import <Foundation/Foundation.h>


@interface XYZSomeView : UIView
@end

#import "XYZSomeView.h"
#import "NSString+NSStringAdditions.h"


@implementation XYZSomeView

- (void)drawRect:(CGRect)rect {

    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);

    NSMutableDictionary *stringAttributes = [[NSMutableDictionary alloc] init];


    [stringAttributes setObject:[UIColor redColor]forKey: NSForegroundColorAttributeName];


    NSString *someString = [NSString stringWithFormat:@"%@", @"S"];

    [someString drawAtPoint:CGPointMake(rect.origin.x, rect.origin.y) withAttributes: stringAttributes];

    NSLog(@"%@", someString);

    CGContextRestoreGState(context);
}

@end

在我的根视图控制器中,我初始化XYZSomeView

#import "XYZRootViewController.h"
#import "XYZSomeView.h"


@implementation XYZRootViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];



    XYZSomeView *someView = [[XYZSomeView alloc] init];

    [self.view addSubview:someView];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

    NSLog(@"%@", @"XYZRootViewController reveived memory warning");
}
@end

问题是我的drawRect没有被调用,是因为我必须自己调用它吗?我认为应该在初始化时调用此方法,而不必调用它。

1 个答案:

答案 0 :(得分:2)

您需要引用当前图形上下文才能使用此功能:docs。您在viewDidLoad:内没有此引用。通常这是在drawRect:内完成的。有一些方法可以在屏幕外生成内容时使用它 - 但这似乎不符合您的需求。

如果要在“viewDidLoad”中向视图控制器添加简单文本,请考虑将具有透明背景的简单UILabel添加到此视图控制器的视图中。

相关问题