How to set the title of UIButton as left alignment?

后端 未结 12 2052
感动是毒
感动是毒 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

提交回复
热议问题