2012-03-26 80 views
0

我有一個鏈接到iboutlet的按鈕。點擊按鈕(* buttonlabel)後,會生成一個標籤。標籤可以在任何位置在屏幕上移動。如果我再次點擊該按鈕,會生成另一個標籤,但我無法再移動第一個標籤。我在互聯網上搜索,發現我必須使用的NSMutableArray,但這似乎並沒有工作:使用NSMutablearray在屏幕上移動UILabels

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

} 

在.H我加:

IBOutlet UILabel *label1; 
    NSMutableArray *array; 

在此先感謝您的幫助

+0

你有一個單一的「=」代替「==」:使用此,而不是測試所有標籤的的在數組中。另外,不要認爲用IBOOutlet裝飾你的陣列是很有意義的。 – onnoweb 2012-03-26 18:56:01

回答

1

編輯:在過去的if語句

- (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; 
     } 
    } 
} 
+0

似乎沒有工作。沒有錯誤,但是,「移動行......以便在後面」意味着什麼。我需要將它放在alloc之後? – Alessandro 2012-03-27 14:44:04

+1

這會工作,但我會在完成配置標籤後將其放入。 (後'label1.backgroundColor = [UIColor clearColor];') – lnafziger 2012-03-27 14:50:24

+0

仍然無法正常工作,我失去了一些東西... – Alessandro 2012-03-27 14:53:26