[英]How to pan inside diagram of UIView
實際上,我在MyView的UIView的子類中繪制了三角形,矩形,五邊形等圖。 當我觸摸MyView上的任何點時(無論該點是否在圖表中),MyView都會移動。 我想觸摸圖表的內部,然后將其移動。 我在MyView上使用平移手勢識別器。請向我建議。
我的代碼是:
在ViewController.m
,
- (void)viewDidLoad
{
MyView *myView = [[MyView alloc] initWithFrame:CGRectMake(0, 100, 200, 100)];
[self.view addSubview:myView];
[super viewDidLoad];
UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scalePiece:)];
[pinchGesture setDelegate:self];
[myView addGestureRecognizer:pinchGesture];
[pinchGesture release];
}
- (void)scalePiece:(UIPinchGestureRecognizer *)gestureRecognizer
{
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
[gestureRecognizer view].transform = CGAffineTransformScale([[gestureRecognizer view] transform], [gestureRecognizer scale], [gestureRecognizer scale]);
[gestureRecognizer setScale:1];
}
}
在MyView.m
,
- (void)drawRect:(CGRect)rect
{
// Drawing code
context =UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
// And draw with a blue fill color
CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 1.0);
// Draw them with a 2.0 stroke width so they are a bit more visible.
CGContextSetLineWidth(context, 2.0);
CGContextMoveToPoint(context, 50.0, 10.0);
CGContextAddLineToPoint(context, 5.0, 70.0);
CGContextAddLineToPoint(context, 150.0, 55.0);
CGContextDrawPath(context, kCGPathFillStroke);
CGContextClosePath(context);
CGContextStrokePath(context);
}
因此,您這里有執行捏手勢的代碼,並且還想做平移手勢嗎? 如果是這樣,我建議您在viewDidLoad中創建平移手勢:
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(movePiece:)];
[myView addGestureRecognizer:panGesture];
[panGesture release];
然后將一個ivar添加到MyView類中:
CGPoint _originalCenter;
最后,擁有移動視圖的方法:
- (void)movePiece:(UIPanGestureRecognizer *)gestureRecognizer
{
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan)
{
_originalCenter = [gestureRecognizer view].center;
}
else if ([gestureRecognizer state] == UIGestureRecognizerStateChanged)
{
CGPoint translation = [gestureRecognizer translationInView:self.view];
[gestureRecognizer view].center = CGPointMake(_originalCenter.x + translation.x, _originalCenter.y + translation.y);
}
}
順便說一句,關於您的代碼的一些觀察:
您正在設置捏手勢的代表,但這不是必需的。 這是通過initWithTarget
方法完成的。
在您的drawRect
方法中,我認為您想在調用CGContextClosePath
之前先調用CGContextDrawPath
。
無論如何,我希望我通過向您展示一個如何使用平移手勢移動子視圖的示例來回答這個問題。 (您說“我正在使用搖動手勢...”,但我假設您的意思是“我想使用搖動手勢...”。)如果我誤解了您的問題,請澄清並重新表述該問題,我們可以再提出一個問題破解它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.