0

我正在开发一个 ER 图编辑器,我有一堆可拖动的 UILabel,但它们都具有相同的名称。我希望能够在使用长按手势识别器同时按下两个 UIlabels 时在两个 UIlabels 之间创建一条线。任何帮助将不胜感激

4

1 回答 1

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 帮助的情况下输入了上面的内容,所以我会提前为拼写错误道歉。)

于 2013-07-15T01:38:53.553 回答