objective c 如何将标签拖放到框上

How to drag label and drop on a box in objective c

我在视图中有几个标签和框,我想将标签拖放到框上,但有些标签隐藏在框下,这是为什么会发生这种情况。我制作了一个子视图 gameLayer 并在此视图上应用了触摸方法。这是代码

for (int i = 0; i < length; i++)
{

    // Create UILabel for Column
    _lbl = [[UILabel alloc] initWithFrame:rect1];
    _lbl.tag = 100+i;
    _lbl.textAlignment = NSTextAlignmentCenter;
    _lbl.backgroundColor = [UIColor blueColor];
    _lbl.textColor = [UIColor whiteColor];
    _lbl.font = [UIFont fontWithName:@"Verdana-Bold" size:17.0];
    [self.gameLayer addSubview:_lbl];
     _lbl.text=[MainArrayFirst objectAtIndex:i];
    [_lbl sizeToFit];

    // Create UILabel Box for ColumnB
    box = [[UILabel alloc] initWithFrame:rect1];
    box.tag = 300+i;
    box.layer.borderColor = [UIColor blueColor].CGColor;
    box.layer.borderWidth = 2.0;
    [self.gameLayer addSubview:box];



  //touches

   -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
      CGPoint pt = [[touches anyObject] locationInView:self.gameLayer];
      _xOffset = pt.x - self.gameLayer.center.x;
      _yOffset = pt.y - self.gameLayer.center.y;

       }

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

       UITouch *touch = [[event allTouches] anyObject];
       CGPoint currentPoint = [touch locationInView:self.gameLayer];

if (touch.view != self.gameLayer)
    [touch view].center = currentPoint;
     }

转到您的故事板 select viewController 并尝试更改 'Document Outline' 上的标签和 "boxes" 的顺序(故事板左侧显示的列表 window).这可能会将您的标签显示在前面。

当你的 for 循环被调用时让我们完成迭代

我 == 0 标签 1 添加 box1 添加

我 == 1 标签 2 添加 box2 添加

现在,当您尝试将 label1 拖到 Box2 上时,它会位于框下方,因为它在它后面添加,所以它的 z 顺序比 label1 更优

因此,为了解决您的问题,您可以设置标签 z 顺序

for (int i = 0; i < length; i++)
{

    // Create UILabel for Column
    _lbl = [[UILabel alloc] initWithFrame:rect1];
    _lbl.tag = 100+i;
    _lbl.textAlignment = NSTextAlignmentCenter;
    _lbl.backgroundColor = [UIColor blueColor];
    _lbl.textColor = [UIColor whiteColor];
    _lbl.font = [UIFont fontWithName:@"Verdana-Bold" size:17.0];
    [self.gameLayer addSubview:_lbl];
     _lbl.text=[MainArrayFirst objectAtIndex:i];
    _lbl.layer.zPosition = 2;
    [_lbl sizeToFit];

    // Create UILabel Box for ColumnB
    box = [[UILabel alloc] initWithFrame:rect1];
    box.tag = 300+i;
    box.layer.borderColor = [UIColor blueColor].CGColor;
    box.layer.borderWidth = 2.0;
    box.layer.zPosition = 1;
    [self.gameLayer addSubview:box];
}

也有很多方法可以做到这一点你可以参考这个 link