objective-cuilabeluitouchtouchesmoved

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


I have a couple of labels and boxes in a view and i want to drag and drop labels on the boxes but the some of labels become hide under the boxes why this happen. I make a subview gameLayer and apply touches methods on this view. Here is code

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;
     }

Solution

  • let go throught the iteration when your for loop called

    i == 0 label1 add box1 add

    i == 1 label2 add box2 add

    now when you try to drag label1 on Box2 it will be below the box because it add after it so its z order is grater than label1

    so for solve your problem you can set your label z order

    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];
    }
    

    also there are many ways to do this stuff you can refers this link