BollMose
BollMose

Reputation: 3498

iOS add UIButton from code: can't control UIButton titlebar text alignment

I have added a UIButton in a UIView,

    UIButton *switchButtonL = [UIButton buttonWithType: UIButtonTypeSystem];
    [switchButtonL addTarget:self action:@selector(switchCity:) forControlEvents:UIControlEventTouchUpInside];
    switchButtonL.frame =  CGRectMake(0, 50, self.screenWidth/2, 30);
    [switchButtonL setTitle: NSLocalizedString(@"switchcity", nil) forState:UIControlStateNormal];
    [switchButtonL setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [switchButtonL setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
    [switchButtonL setBackgroundColor:[UIColor clearColor] ];
    switchButtonL.titleLabel.textAlignment = NSTextAlignmentLeft; // this line can't work
    switchButtonL.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:18];
    [self addSubview:switchButtonL];

and the comment line can't work, the text align center always.

Upvotes: 0

Views: 158

Answers (3)

Suhail kalathil
Suhail kalathil

Reputation: 2693

Try this..

switchButtonL.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
switchButtonL.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

Upvotes: 1

souvickcse
souvickcse

Reputation: 7804

enter image description here

You can change it from xib shown in the above image. And if you want to change it by code use this with your required position:

self.yourbtn.titleEdgeInsets=UIEdgeInsetsMake(topVal, leftVal, downVal, rightVal); 

Upvotes: 1

Scimmia Alpha
Scimmia Alpha

Reputation: 211

Try substitute

switchButtonL.titleLabel.textAlignment = NSTextAlignmentLeft; // this line can't work

With:

switchButtonL.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
switchButtonL.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

Upvotes: 2

Related Questions