连接通过线路连接的可拖动移动UI按钮

时间:2011-10-29 12:42:13

标签: iphone ios uibutton

如何使用线路连接两个移动(可拖动)UIButton?

问题:当我连接时它看起来很不错,但是当我尝试拖动一个按钮时,该线保持在同一位置。

我想做一些像Discover Music或Discover Apps这样的事情,用UIButtons构建移动图作为节点。

以下是我的代码示例:

- (CGRect)currentRect {
return CGRectMake (firstTouch.x,
firstTouch.y,
lastTouch.x - firstTouch.x,
lastTouch.y - firstTouch.y);
}
- (void)drawRect:(CGRect)rect {
self.currentColor = [UIColor redColor];

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, currentColor.CGColor);

CGContextSetFillColorWithColor(context, currentColor.CGColor);

CGContextMoveToPoint(context, firstTouch.x, firstTouch.y);
CGContextAddLineToPoint(context, lastTouch.x, lastTouch.y);
CGContextStrokePath(context);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch *touch = [touches anyObject];
firstTouch = [touch locationInView:self];
lastTouch = [touch locationInView:self];
[self setNeedsDisplay];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
lastTouch = [touch locationInView:self];

redrawRect = CGRectUnion(redrawRect, self.currentRect);
redrawRect = CGRectInset(redrawRect, -2.0, -2.0);
[self setNeedsDisplayInRect:redrawRect];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
lastTouch = [touch locationInView:self];

redrawRect = CGRectUnion(redrawRect, self.currentRect);
[self setNeedsDisplayInRect:redrawRect];
}

Screenshot

1 个答案:

答案 0 :(得分:0)

您应首先清除上下文。尝试:

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
    CGContextFillRect(context, self.bounds);

    self.currentColor = [UIColor redColor];
    CGContextSetLineWidth(context, 2.0);
    CGContextSetStrokeColorWithColor(context, currentColor.CGColor);
    //...

我没有测试过代码,但应该有帮助