Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++;
}
like image 419
himan Avatar asked Mar 07 '13 11:03

himan


2 Answers

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;
like image 160
dsgriffin Avatar answered Oct 06 '22 00:10

dsgriffin


Use this :

button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill; 


button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
like image 42
Vineet Singh Avatar answered Oct 06 '22 01:10

Vineet Singh