使用NSMutablearray在屏幕上移动UILabels

时间:2012-03-26 18:31:07

标签: ios xcode

我有一个链接到iboutlet的按钮。单击按钮(* buttonlabel)时,会生成标签。标签可以在任何位置在屏幕上移动。如果我再次单击该按钮,则会生成另一个标签,但我无法再移动第一个标签。我在互联网上搜索,发现我必须使用NSMutablearray,但这似乎不起作用:

in.m

-(IBAction)button3Pressed:(id)sender{

  self.buttonBrush.selected = NO;
self.buttonBrush.highlighted = NO;
self.buttonlabel.selected = YES;
self.buttonlabel.highlighted = YES;
self.buttontextbox.selected = NO;
self.buttontextbox.highlighted = NO;


CGRect labelFrame = CGRectMake( 400, 100, 100, 30);

label1 = [[UILabel alloc] initWithFrame: labelFrame];
[label1 setText: @"Untitled"];
[label1 setTextColor: [UIColor orangeColor]];
[self.view addSubview:label1];
label1.backgroundColor = [UIColor clearColor];

 if (array == nil) array = [[NSMutableArray alloc]init];
  [array addObject:label1];

}

然后

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

//label1

if (buttonlabel.selected == YES){

    UITouch *touch = [touches anyObject];   
    CGPoint location = [touch locationInView:self.view];


    UIView *touchedView = [touch view];

    if ([array containsObject:touchedView]){

        touchedView.center = location;  
    }
}

 }

in .h我补充道:

 IBOutlet UILabel *label1;
    NSMutableArray *array;

提前感谢您的帮助

1 个答案:

答案 0 :(得分:1)

编辑:改用它来测试数组中的所有标签:

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

    for (UILabel *label in array) {
        CGPoint localLocation = [label convertPoint:location fromView:self.view];
        if ([label pointInside:localLocation withEvent:nil]) {
            label.center = location;
            break;
        }
    }
}