在将视图添加到超级视图和setNeedsDisplay之后,不会调用子视图中的Objective C drawRect

时间:2015-03-05 23:00:01

标签: subview drawrect superview setneedsdisplay

我有一个视图: DragView 和一个视图: GameAreaView ,并在 GameViewController 中声明 GameAreaView 。< / p>

问题是我的自定义子视图:DragView没有像预期的那样drawRect,在超级视图中没有绘制任何内容。

GameViewController.m

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
...... get touch point , but haven't use it

// Initialise a dragView when user touches in gameAreaView
DragView *agentDragger = [[DragView alloc] initWithFrame:CGRectMake(10, 10,     
50, 50)];

[self.gameAreaView addSubview:agentDragger];

[[self gameAreaView] setNeedsDisplay];
}

GameAreaView.m

-(void)drawRect:(CGRect)rect {
    NSLog(@"I am GameAreaView Rect!!");
}

DragView.m - (id)initwithFrame::( CGRect)frame

-(id) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        NSLog(@"1.Hi i am in if ");
    }
    return self;
}

- (void)drawRect:(CGRect)rect {

   [MyStyleKitAgent drawAgentNodeWithFrame:_frame
                        longPressed:_isLongPressed
                               vname:_name
                             pressed:_isPressed];


// Test for draw lines
NSLog(@"I am in DragView");

但如果我 更改 更新>

-(id) initWithImage:(UIImage *) anImage
{
    self = [super initWithImage:anImage];
    return self;
}

带有图像的子视图显示在GameAreaView中,没有使用drawRect。

我也尝试过使用 setNeesDisplayInRect ,没有任何变化。

为什么在使用 - (id)initwithFrame时没有调用 DragView.m 中的drawRect? 为什么会这样? 以及如何解决它?

1 个答案:

答案 0 :(得分:0)

您需要通过setNeedsDisplay调用您的子视图而不是您的主视图

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    //...... get touch point , but haven't use it

// Initialise a dragView when user touches in gameAreaView
 DragView *agentDragger = [[DragView alloc] initWithFrame:CGRectMake(10, 10,     
  50, 50)];

 [self.gameAreaView addSubview:agentDragger];

  [agentDragger setNeedsDisplay];
}