user2277872
user2277872

Reputation: 2973

why do my UILabels not appear in the right spaces

I have a game. I am loading 3 image views with label objects. Then I load 5, and then 7. Just yesterday I had the same issue, and I found the answer to be making the autoresizing mask on the labels to none. Well, I did that, it fixed it, but now the issue is back today. This is confusing, and I have no clue how to fix it.

My question is, why is this still happening if i've already done that? and how can I fix it?

Here is my code:

  // random word from array of object
    NSString *randomWord = [self.objects objectAtIndex:randomObject];

    [self.imageViews[i] addSubview:self.labels[i]];
    [self.labels[i] setCenter:[self.imageViews[i] center]];

    // all labels setting text and alignment
    [self.labels[i] setText:randomWord];
    [self.labels[i] setTextAlignment:NSTextAlignmentCenter];

    // adding words to alphabetical array
    [self.alphabeticalWords addObject:randomWord];
    NSLog(@"%@", randomWord);
    //NSLog(@"%@", self.alphabeticalWords);

    [self.labels[i] sizeToFit];
    [self.labels[i] setAutoresizingMask:UIViewAutoresizingNone];
    [self.imageViews[i] setUserInteractionEnabled:YES];
    [self.imageViews[i] addGestureRecognizer:panGesture];

and here is the issue

enter image description here

any help is very much appreciated.

Upvotes: 0

Views: 65

Answers (1)

Dima
Dima

Reputation: 23624

One issue is your use if the view hierarchy and center. You are adding the labels as subviews to the image views and then using center to try to overlay them. The definition of center is:

The center is specified within the coordinate system of its superview and is measured in points. Setting this property changes the values of the frame properties accordingly.

Setting the center of a subview to the center of its superview will not necessarily behave the way you want because they are not sitting in the same coordinate space.

You should be using the bounds of the image view which is what represents its internal coordinate space. What you probably want to do is something like this instead:

[self.labels[i] setCenter:CGPointMake((self.imageViews[i].bounds.size.width / 2), (self.imageViews[i].bounds.size.height / 2)];

Upvotes: 1

Related Questions