0

After adding four _labelView by -addLabel, I'd like to move all _labelView at random by -moveLabel.
LabelView is subclass of UIView.

But in case of this code, I can move only one _labelView I have added at the last.
Looking NSLog(@"%d", _viewsArray.count), it outputs "1".
How do I fix it to move all _labelView?

enter image description here

@property (nonatomic, strong) LabelView* labelView;
@property (nonatomic, strong) NSMutableArray* viewsArray;

- (void)addLabel
{
    _viewsArray = [[NSMutableArray alloc]init];
    _labelView = [[LabelView alloc]initWithFrame:CGRectMake(0, 0, 200, 25)];
    [_viewsArray addObject:_labelView];
    for (_labelView in _viewsArray){
        [self.view addSubview:_labelView];
    }
    NSLog(@"%d", _viewsArray.count);
}

- (void)moveLabel
{
    int n;
    CGPoint labelFrame;
    for (_labelView in _viewsArray)
    {
        n = arc4random() % 4;
        switch (n) {
            case 0: labelFrame = CGPointMake(30, 50);
                break;
            case 1: labelFrame = CGPointMake(30, 100);
                break;
            case 2: labelFrame = CGPointMake(30, 150);
                break;
            case 3: labelFrame = CGPointMake(30, 200);
                break;
            default:
                break;
        }
        [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationCurveEaseIn
                         animations:^{_labelView.center = labelFrame;} completion:^(BOOL finished){}];
    }
    NSLog(@"%d", _viewsArray.count);
}
3
  • 1
    whenever you call addLabelyou are creating a new empty mutable array... Commented Jun 2, 2014 at 14:39
  • You only ever put one element in each array you create. Commented Jun 2, 2014 at 14:39
  • Moreover, after you fix that problem, the addLabel code will re-add all of it's labels to self.view. Don't loop that array on the add. Commented Jun 2, 2014 at 14:41

3 Answers 3

4

In your addLabel method you allocate the NSMutableArray every single time you add new label:

_viewsArray = [[NSMutableArray alloc]init];

so you will have just one object in that array. Simple move this line to viewDidLoad method (or some init method if it;s not view controller subclass) and it should fix it.

Sign up to request clarification or add additional context in comments.

Comments

0

You are allocating a new _viewsArray everytime addView is called! You should rather allocate the Array at viewDidLoad or something, and then just use it

Comments

0

The most simple fix...

- (void)addLabel {
    if (_viewsArray == nil) {
        _viewsArray = [[NSMutableArray alloc] init];
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.