2013-05-05 62 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!把它放在筆尖上。