简体   繁体   中英

How to show the title under the UIButton?

I have used the title inset to display the text name under the UIButton .

Here's my code and the output:

 [button setTitleEdgeInsets:UIEdgeInsetsMake(60, 0, 0, 0)];

在此处输入图片说明

Here's my expected output:

在此处输入图片说明

I have used the UIButton and set the title and UIImage as background. So how to show the title label under the UIButton ?

What you're trying to do is correct; you just need to set the inset edges as done below. Then you need to increase your button frame so that it can hold the title and image in the same time.

[button setTitleEdgeInsets:UIEdgeInsetsMake(60, 0, 0, 0)];

[button setImageEdgeInsets:UIEdgeInsetsMake(0.0f, 0.f, button.titleLabel.frame.size.height, 0.f)];

This can also be done via storyboards as @VD Patel suggests that is up to you which approach you prefer.

You could also do this with a separate UIImageview and a button that would be easier to handle and would be more efficient.

Please Select button in xib first. then select Attribute Inspector, in this Select Title in "Edge" and set appropriate "Inset" as per Requirements.

please take a look with below code and set insets as per your Requirements.

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(0, 0, self.view.bounds.size.width, 40);
[myButton setImage:[UIImage imageNamed:@"imageName"] forState:UIControlStateNormal];
[myButton setTitle:@"Rate us on app store" forState:UIControlStateNormal];
[myButton setTitleEdgeInsets:UIEdgeInsetsMake(2, 50, 2, 20)];//set ur title insects myButton
[myButton setImageEdgeInsets:UIEdgeInsetsMake(2, -200, 2, 2)];//make negative edge for left side
[myButton setBackgroundColor:[UIColor greenColor]];
[self.view myButton];

Create an UIImageView , UILabel and UIButton . And later add ImageView and Label as subview to Button.

    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 200, 100)];
    lbl.textAlignment = NSTextAlignmentCenter;
    [lbl setText:@"Mono"];

    UIImageView * imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    imgView.image = [UIImage imageNamed:@"your_image.png"];
    [imgView setUserInteractionEnabled:NO];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addSubview:imgView];
    [btn addSubview:lbl];
    [btn setFrame:CGRectMake(0, 20, 200, 300)];
    [btn addTarget:self action:@selector(OnButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

Try adding this code in viewDidLoad Method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM