1

I have a class which mimics a button. It contains one label, which I'm trying to align centrally (horizontally). No matter what I try, the label stays on the left hand side, leading me to think this is more complicated than it seems. Here's the only initialization/setup code:

-(CCButtonLayer*)initWithText:(NSString*)text bgColor:(ccColor4B)color width:(GLfloat)width height:(GLfloat)height {
    self = [super initWithColor:color width:width height:height];
    self.lbl = [CCLabelTTF labelWithString:text fontName:@"Marker Felt" fontSize:22];
    self.lbl.horizontalAlignment = kCCTextAlignmentCenter;
    [self.lbl setHorizontalAlignment:kCCTextAlignmentCenter];
    self.lbl.color = ccc3(0,0,0);
 //   self.lbl.contentSize = CGSizeMake(width, height); // no effect anyway
    self.lbl.anchorPoint = CGPointZero;
    self.lbl.position = CGPointZero;
    [self addChild:self.lbl];
    return self;
}
Echilon
  • 10,064
  • 33
  • 131
  • 217

3 Answers3

3

I removed the alignment properties of the label and aligned it manually instead. Clearly something which I can't see is happening, perhaps there's another offset as you said @LearnCocos2D

// this worked
CGSize textSize = [self.lbl.string sizeWithFont:[UIFont fontWithName:fontName size:fontSize]];
self.lbl.anchorPoint = CGPointZero;
self.lbl.position = ccp(textSize.width /2.0f, textSize.height/2.0);
gdbj
  • 16,102
  • 5
  • 35
  • 47
Echilon
  • 10,064
  • 33
  • 131
  • 217
1
self.lbl.anchorPoint = CGPointZero;
self.lbl.position = CGPointZero;

It's these two lines which are determining the position of your label.

Try setting them to:

self.lbl.anchorPoint = ccp(0.5, 0.5);  //This is default, you could omit
self.lbl.position = ccp(self.contentSize.width / 2.0f, self.contentSize.height / 2.0f);

I have assumed that "self" is the button and that it's content size has been set at this point

James Webster
  • 31,873
  • 11
  • 70
  • 114
1

As James said, changing the anchorPoint affects the alignment. So don't assign CGPointZero because that will align the lower left corner with the parent's position.

The fact that you still see no change might indicate that you haven't considered the label's position is in fact an offset to the parent's position. Now if you have changed the parent's anchorPoint as well, the position of the label will be an offset from the parent's lower left corner.

Long story short: leave the anchorPoint unchanged. Except for the label, where you can use the anchorPoint to affect alignment.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
  • There's definitely something else happening here. I eventually got this working using the method below. – Echilon Aug 19 '12 at 14:36