himan himan - 1 month ago 16
Objective-C Question

Aligning a UIButton's text?

I am generating some buttons. In the button I am showing date and a reference id given by the user. I want these data to be left aligned in the button.

What I have tried:

[button.titleLabel setTextAlignment:UITextAlignmentLeft];
button.titleLabel.textAlignment = UITextAlignmentLeft;


But this doesn't work.

- (void)viewDidLoad
{
[super viewDidLoad];
[scrollView setScrollEnabled:YES];
[scrollView setContentSize:CGSizeMake(320, 500)];

int i = 0;

for (CalculatorData *data in calcDatas) {

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];


button.frame = CGRectMake(1 , 20 + i*40, 295, 30);

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy HH:MM:SS"];

NSString *dateString = [dateFormat stringFromDate:data.updateDate];

NSString *title = [NSString stringWithFormat:@"%@ : %@",dateString,[data dataKey]];


[button setTitle:title forState:UIControlStateNormal];


[button addTarget:self action:@selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = data.calcId;


[scrollView addSubview:button];
i++;
}

Answer

You can use the contentHorizontalAlignment:

"The horizontal alignment of content (text or image) within the receiver."

and the contentVerticalAlignment properties for this:

"The vertical alignment of content (text or image) within the receiver."

Example usage:

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;