2

drawRect メソッドに引数を渡すときに問題が発生しました。メソッドで指定された引数を変更します。

drawRect で長方形のフレームを直接設定すると正常に動作するため、引数の受け渡しに問題があるはずです。

たとえば、変更されるので、私のコードはこれです。

ServiceAppViewController.m

-(void) initTransformBoxes{
TransformBox *transform = [[TransformBox alloc] initWithFrame:CGRectMake(20, _transformArrowView.frame.origin.y+65,                                                                      _transformArrowView.frame.size.width,120)];

[transform setBackgroundColor:[UIColor grayColor]];

[transform drawRect:CGRectMake(0, 0, 20, 20)];
[self.view addSubview:transform];


}

}

TransformBox.m

-(void) drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetLineWidth(context, 2.0);

CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);

//but when I do it hard wired it works?
CGRect rectangle = CGRectMake(0, 0, 20, 20);
CGContextAddRect(context,rectangle);
//instead of this
//    CGContextAddRect(context,rect);

CGContextStrokePath(context);
}

もう 1 つの質問は、静的な drawRect メソッドを作成できるかどうかです。.h ファイルで drawRect をオーバーライドしようとしましたが、呼び出されませんでしたか?

前もって感謝します!

4

1 に答える 1

1

電話してはいけない[transform drawRect:CGRectMake(0, 0, 20, 20)];

このdrawRect:メソッドは、ビューが表示されると自動的に呼び出され、rectパラメーターは実際にはビューのフレームです。

ビューにパラメーターを渡して描画する場合は、それをプロパティとしてビューに渡しますTransformBox

(親ビューに追加した後)変更する必要がある場合は、使用します

[transform setSmallRect:CGRectMake(0, 0, 20, 20)];
[transform setNeedsDisplay];

drawRect が自動的に呼び出されます。drawRect メソッド内でそのプロパティを使用します。

ServiceAppViewController.m

-(void) initTransformBoxes
{
    TransformBox *transform = [[TransformBox alloc] initWithFrame:CGRectMake(20, _transformArrowView.frame.origin.y + 65,                                                                      _transformArrowView.frame.size.width, 120)];

    [transform setBackgroundColor:[UIColor grayColor]];

    [transform setSmallRect:CGRectMake(0, 0, 20, 20)];
    [self.view addSubview:transform];
}

drawRect:ビューが追加された後に呼び出されます。

TransformBox.m

-(void) drawRect:(CGRect)rect{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, 2.0);

    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);

    CGRect rectangle = [self smallRect];
    CGContextAddRect(context,rectangle);

    CGContextStrokePath(context);
}
于 2013-07-29T14:36:11.213 に答える