0

以下を UIView に配置し、それをストーリーボード ビューに接続することで、線を引くことができます。

- (void)drawRect:(CGRect)rect {
CGContextRef  context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 5.0);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGFloat components[] = {0.0, 0.0, 1.0, 1.0};
CGColorRef color = CGColorCreate(colorspace, components);
CGContextSetStrokeColorWithColor(context, color);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, 10, 50);
CGContextStrokePath(context);
CGColorSpaceRelease(colorspace);
CGColorRelease(color);

}

しかし、私がやりたいのは、ボタンが押されるたびに線を引くことです。これを行うには、IBAction にコードを記述する必要があると想定しています。私の問題は、エラーが発生するため、上記のコードを IBAction に単純に配置できないことです。

- (IBAction)draw:(id)sender{
 //Place code here

}

私の質問は、ボタンが押されるたびに線を引くにはどうすればよいですか?

同様のコードを接続して、ボタンを押すとトリガーされる別の線を描画するにはどうすればよいですか

4

2 に答える 2

2

UIView を描画するには、UIView をサブクラス化する必要があります

.h で

   @MyCustomView : UIView {
    }

    @end

メートルで

@implementation MyCustomView

- (void) drawRect: (CGRect) rect
{
        CGContextRef  context = UIGraphicsGetCurrentContext();
        CGContextSetLineWidth(context, 5.0);
        CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
        CGFloat components[] = {0.0, 0.0, 1.0, 1.0};
        CGColorRef color = CGColorCreate(colorspace, components);
        CGContextSetStrokeColorWithColor(context, color);
        CGContextMoveToPoint(context, 0, 0);
        CGContextAddLineToPoint(context, 10, 50);
        CGContextStrokePath(context);
        CGColorSpaceRelease(colorspace);
        CGColorRelease(color);
    }

あなたのViewControllerで

-(void)methodCallCustomView{

       } 

- (IBAction)draw:(id)sender{
   [self methodCallCustomView];
    }
于 2012-06-01T20:01:08.767 に答える
1

ボタンを押したときに drawRect: メソッドが呼び出されるようにしますか? その場合は、メッセージ setNeedsDisplay を drawRect: コードを持つビューに送信します。

于 2012-06-01T16:28:17.997 に答える