drawRect被调用但其中的代码在运行时没有被执行?

时间:2013-05-05 00:43:41

标签: ios core-graphics drawrect

我选择了XCODE 4.5.2中的单一视图应用程序模板。我有一个appdelegate,一个带有RDViewController.xib的viewcontroller,我已经创建了一个类型的UIView类Graphics。我还有Graphics.h和Graphics.m(其中的drawRect方法)。在GraphicsController.m中有一个Graphics类的图形属性。当运行drawRect方法被调用但在模拟器上没有绘制时。 Graphics类中的initWithFrame方法未被调用。 RDViewController.xib是Graphics的子类。

在appdelegate中

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[RDViewController alloc] initWithNibName:@"RDViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

我只写了一个ViewController:

@implementation RDViewController

@synthesize graphics;

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

    [self.graphics setNeedsDisplay];
}
UIView子类Graphics

中的

@implementation GraphicsView

- (id)initWithFrame:(CGRect)frame
{
    NSLog(@"Frame: %@", NSStringFromCGRect(frame));
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    UIFont *helveticaBold;

    [UIFont fontWithName:@"HelveticaNeue-Bold" size:40.0f];

    NSString *myString = @"Test string function";

    [myString drawInRect:CGRectMake(20.0f,20.0f,40.0f,160.0f)
                withFont:helveticaBold];

    self.backgroundColor = [UIColor whiteColor];
}

运行时,调用drawRect方法,但模拟器上没有绘制任何内容。 Graphics类中的initWithFrame方法未被调用。 RDViewController.xib是Graphics的子类。

2 个答案:

答案 0 :(得分:1)

您永远不会设置字体。这样做:

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    UIFont *helveticaBold = [UIFont fontWithName:@"HelveticaNeue-Bold" size:40.0f];

    NSString *myString = @"Test string function";

    [myString drawInRect:CGRectMake(20.0f,20.0f,40.0f,160.0f)
                withFont:helveticaBold];
}

背景颜色应该在initWithFrame:方法中设置。

答案 1 :(得分:0)

请勿在{{1​​}}中设置self.backgroundColor!将它设置在笔尖中。