How to set the title of UIButton as left alignment?

后端 未结 12 1980
感动是毒
感动是毒 2020-11-27 08:34

I need to display the email address from left side of a UIButton, but it is being positioned in the centre.

Is there any way to set the alignment to the

相关标签:
12条回答
  • 2020-11-27 09:16

    There is a small error in the code of @DyingCactus. Here is the correct solution to add an UILabel to an UIButton to align the button text to better control the button 'title':

    NSString *myLabelText = @"Hello World";
    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    // position in the parent view and set the size of the button
    myButton.frame = CGRectMake(myX, myY, myWidth, myHeight); 
    
    CGRect myButtonRect = myButton.bounds;
    UILabel *myLabel = [[UILabel alloc] initWithFrame: myButtonRect];   
    myLabel.text = myLabelText;
    myLabel.backgroundColor = [UIColor clearColor];
    myLabel.textColor = [UIColor redColor]; 
    myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0];   
    myLabel.textAlignment = UITextAlignmentLeft;
    
    [myButton addSubview:myLabel];
    [myLabel release];
    

    Hope this helps....

    Al

    0 讨论(0)
  • 2020-11-27 09:17

    For Swift 2.0:

    emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left  
    

    This can help if any one needed.

    0 讨论(0)
  • 2020-11-27 09:24

    You can also use interface builder if you don't want to make the adjustments in code. Here I left align the text and also indent it some:

    UIButton in IB

    Don't forget you can also align an image in the button too.:

    enter image description here

    0 讨论(0)
  • 2020-11-27 09:24

    Swift 4+

    button.contentHorizontalAlignment = .left
    button.contentVerticalAlignment = .top
    button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    
    0 讨论(0)
  • 2020-11-27 09:25

    Set the contentHorizontalAlignment:

    emailBtn.contentHorizontalAlignment = .left;
    

    You might also want to adjust the content left inset otherwise the text will touch the left border:

    emailBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    
    // Swift 3 and up:
    emailBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0);
    
    0 讨论(0)
  • 2020-11-27 09:26

    Using emailBtn.titleEdgeInsets is better than contentEdgeInsets, in case you don't want to change the whole content position inside the button.

    0 讨论(0)
提交回复
热议问题