简单的UIView drawRect未被调用

Cod*_*Guy 6 uiview ios

我无法弄清楚这里的问题是什么.我有一个非常简单的UIViewController,它有一个非常简单的viewDidLoad方法:

-(void)viewDidLoad {

    NSLog(@"making game view");
    GameView *v = [[GameView alloc] initWithFrame:CGRectMake(0,0,320,460)];

    [self.view addSubview:v];

    [super viewDidLoad];
}
Run Code Online (Sandbox Code Playgroud)

我的GameView初始化如下:

@interface GameView : UIView {
Run Code Online (Sandbox Code Playgroud)

它只是有一个新的drawRect方法:

- (void)drawRect:(CGRect)rect
{

    [super drawRect:rect];

    NSLog(@"drawing");
}
Run Code Online (Sandbox Code Playgroud)

在我的控制台中,我看到正在打印"制作游戏视图",但从未打印过"绘图".为什么?为什么我的自定义UIView中的drawRect方法不被调用.我真的只想在屏幕上画一个圆圈.

Eyt*_*tan 12

您是否尝试在视图的初始化中指定帧?因为您要创建自定义UIView,所以需要在调用绘图方法之前指定视图的框架.

尝试将viewDidLoad更改为以下内容:

NSLog(@"making game view");
GameView *v = [[GameView alloc] initWithFrame:CGRectMake(0,0,320,460)];


if (v == nil)
    NSLog(@"was not allocated and/or initialized");

[self.view addSubview:v];

if (v.superview == nil)
    NSLog(@"was not added to view");

[super viewDidLoad];
Run Code Online (Sandbox Code Playgroud)

让我知道你得到了什么.