Hello all! I'm working on dynamic buttons depending on the plist file. The buttons show up fine, however I'm in a bit of pain with calculating the width of the buttons, because they are not aligned to the left like they suppose to. Code: for(int a=0; a < [currentButtons count]; a++) { //adding 10 px for each character, plus 10 extra for some 'padding' in case there is a background color float width = ([[currentButtons objectAtIndex: a] length] * 10) + 10; float horizPos = 10; if(buttonPosition == 2) { horizPos = centerX - (width / 2); } if(buttonPosition == 3) { horizPos = naviView.frame.size.width - width - 10; } UIButton *theButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [theButton setTag: a]; [theButton setTitle:[currentButtons objectAtIndex: a] forState:UIControlStateNormal]; theButton.frame = CGRectMake(horizPos, yOffset, width, 23.0); [theButton.titleLabel setTextAlignment: NSTextAlignmentLeft]; What is the best way to calculate the width of my buttons ? (I assume it has to do with the width of my buttons) When I add a background color to the buttons, I see that the frame is correct, but the text is not.
This was entertaining enough to have a look at. I made an assumption that when you say you want your text left justified, you mean within the whole width of the button. It seems that the NSTextAlignmentLeft that you applied only applies to the titleLabel of the button, not the whole width of the button. It turns out to be useful for the fine tuning. That label is a subview within the button. Alter the background color of the titleLabel to see what iOS is up to when laying it out. Through a little experimenting, I found the following to be functional. I'm moving the horizontal origin of the title to the left. Code: [COLOR="Green"]// Truely Left Justify the text in a button.[/COLOR] CGRect titleFrame = theButton.titleLabel.frame; titleFrame.origin.x = 0.0; [COLOR="Green"]// You'll want to add a little padding.[/COLOR] theButton.titleLabel.frame = titleFrame; If you are using SDK 7 or later, you can do the following to calculate the rectangle that your text is using. Code: CGSize size = [[currentButtons objectAtIndex: a] sizeWithAttributes: @{NSFontAttributeName: [UIFont systemFontOfSize:[UIFont buttonFontSize]]}]; width = size.width;
lol I never thought that titlelabel is an subview of uibutton... It works great! Exactly what you are saying, it now does justify on the frame of the button itself the titleframe is perfect now with an padding of 10 and together with the Code: CGSize size = [[currentButtons objectAtIndex: a] sizeWithAttributes: @{NSFontAttributeName: [UIFont systemFontOfSize:[UIFont buttonFontSize]]}]; I will remind this forever! The size is perfect as well! This is amazing. Thank you very much xStep!