2013-05-05 84 views
0

我从XCODE 4.5.2中选择了单视图应用程序模板。我有一个appdelegate,一个带有RDViewController.xib的视图控制器,我制作了一个UIView类Graphics。另外我有Graphics.h和Graphics.m(drawRect方法)。 Graphics类的viewController.m中有一个图形属性。当运行被调用的drawRect方法但在模拟器上没有绘制时。 Graphics类中的initWithFrame方法未被调用。 RDViewController.xib是Graphics的子类。drawRect被调用,但它内部的代码在运行时没有被执行?

中的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; 
} 

只在一个视图控制器我已经写:

@implementation RDViewController 

@synthesize graphics; 

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

    [self.graphics setNeedsDisplay]; 
} 

在UIView子类图形

@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的子类。

+0

“图形类中的initWithFrame方法未被调用”没问题。如果UIView是从一个nib实例化的,你不会期望这个方法被调用。而是调用'initWithCoder'。 – matt 2013-05-05 00:51:59

回答

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:方法进行设置。

+0

你的意思是'initWithCoder'。 'initWithFrame'永远不会被调用。 – matt 2013-05-05 00:55:09

+0

是的initWithFrame永远不会被调用,但我必须实现initWithCoder只是为了改变背景? – ShaluRaj 2013-05-05 01:09:29

+0

你很可能可以在IB中设置视图的背景颜色,那么你不需要为此只实现'initWithCoder'。 – rmaddy 2013-05-05 01:53:52

0

请勿在drawRect中设置self.backgroundColor!把它放在笔尖上。

相关问题