我正在开发一个ER图编辑器,我有一堆可拖动的UILabel,但它们都有相同的名称。我希望能够在使用长按手势识别器将两者按在一起时在两个UI标签之间创建一条线。任何帮助将非常感激
答案 0 :(得分:1)
您可以在这两个标签共享的超级视图上创建长按手势,例如:
UILongPressGestureRecognizer *twoTouchLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self
action:@selector(handleLongPress:)];
twoTouchLongPress.numberOfTouchesRequired = 2;
[self.view addGestureRecognizer:twoTouchLongPress];
然后你可以写一个手势处理程序:
- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture
{
if (gesture.state == UIGestureRecognizerStateBegan)
{
CGPoint location0 = [gesture locationOfTouch:0 inView:gesture.view];
CGPoint location1 = [gesture locationOfTouch:1 inView:gesture.view];
if ((CGRectContainsPoint(self.label0.frame, location0) && CGRectContainsPoint(self.label1.frame, location1)) ||
(CGRectContainsPoint(self.label1.frame, location0) && CGRectContainsPoint(self.label0.frame, location1)))
{
NSLog(@"success; draw your line");
}
else
{
NSLog(@"failure; don't draw your line");
}
}
}
在更新的评论中,您建议您创建一个本地UILabel
变量,然后将生成的标签添加到视图中。这很好,但你真的想要维护一个支持模型,它可以捕获你在视图中所做的事情。为简单起见,我假设您将拥有这些标签的数组,例如:
@property (nonatomic, strong) NSMutableArray *labels;
然后你在某个时候初始化(例如viewDidLoad
):
self.labels = [[NSMutableArray alloc] init];
然后在向视图添加标签时,在数组中添加对它们的引用:
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(xVal, yVal, 200.0f, 60.0f)];
label.text = sentence;
label.layer.borderColor = [UIColor blueColor].CGColor;
label.layer.borderWidth = 0.0;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont systemFontOfSize:19.0f];
[self.view addSubview:label];
[self.labels addObject:label];
然后,您的手势可以执行以下操作:
- (UILabel *)labelForLocation:(CGPoint)location
{
for (UILabel *label in self.labels)
{
if (CGRectContainsPoint(label.frame, location))
return label; // if found one, return that `UILabel`
}
return nil; // if not, return nil
}
- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture
{
if (gesture.state == UIGestureRecognizerStateBegan)
{
CGPoint location0 = [gesture locationOfTouch:0 inView:gesture.view];
CGPoint location1 = [gesture locationOfTouch:1 inView:gesture.view];
UILabel *label0 = [self labelForLocation:location0];
UILabel *label1 = [self labelForLocation:location1];
if (label0 != nil && label1 != nil && label0 != label1)
{
NSLog(@"success; draw your line");
}
else
{
NSLog(@"failure; don't draw your line");
}
}
}
坦率地说,我宁愿看到这个由合适的模型支持,但这是一个超出简单Stack Overflow答案范围的更复杂的对话。但希望上面的内容可以让您了解它的外观。 (顺便说一句,我只是在没有Xcode协助的情况下输入上述内容,所以我会提前为拼写错误道歉。)