UIButton with both image and text possible?

前端 未结 10 1424
轮回少年
轮回少年 2020-12-02 08:57

I have a button of size width 200 and height 270. I want to have text and image on the same button. Not as a background image on that text. Instead of this, I want to displa

相关标签:
10条回答
  • 2020-12-02 09:07

    Use the concept of subviews. Take 3 controls, UIButton (200x270), UILabel (200x120) and UIImageView (200x150). Assign the image to the UIImageView and set the text for the UILabel. Position your label and imageview controls based upon the (x,y) location of the UIButton.

    In the end, you should have something like:

    For the following instances:

    UIButton *button;
    UILabel *label;
    UIImageView *imageView;
    
    [button addSubView:imageView];
    [button addSubView:label];
    
    0 讨论(0)
  • 2020-12-02 09:16

    You can use this code,it will serve your purpose

    .h file code
    IBOutlet UIButton *testBtn;
    
    .m file code
    [testBtn setImage: [UIImage imageNamed:@"Image name.png"] forState:UIControlStateNormal];
    [testBtn setTitleEdgeInsets:UIEdgeInsetsMake(70.0, -150.0, 5.0, 5.0)];
    [testBtn setTitle:@"Your text" forState:UIControlStateNormal];
    

    Adjust the coordinates and size of your button as your requirement.This is a sample code to guide you.

    PS:Take a UIButton in the nib file>Make it a custom button>Connect the IBOutlet to your custom button in the nib file.Thats it.

    0 讨论(0)
  • 2020-12-02 09:16

    In Swift 3

    let button = UIButton()
    
    //make sure the image (jpg, png) you are placing in the button
    //is about the right size or it will push the label off the button
    
    //add image
    let image = UIImage(named:"my_button_image")
    button.setImage(image, for: .normal)
    button.imageView?.contentMode = .scaleAspectFit
    button.imageEdgeInsets = UIEdgeInsets(top:0, left:-30, bottom:0, right:0) //adjust these to have fit right
    
    //add title
    button.setTitle("Fan", for: .normal)
    button.titleEdgeInsets = UIEdgeInsets(top:0, left:10, bottom:0, right:0) //adjust insets to have fit how you want
    
    //add button to your view - like in viewDidLoad or your own custom view setup
    addSubview(button)
    

    Don't forget to set anchors if doing so programmatically for it to appear/attach it to your button reference in Interface Builder if using a storyboard

    0 讨论(0)
  • 2020-12-02 09:27

    swift version:

    var button = UIButton()
    
    newGameButton.setTitle("Новая игра", for: .normal)
    newGameButton.setImage(UIImage(named: "energi"), for: .normal)
    newGameButton.backgroundColor = .blue
    newGameButton.imageEdgeInsets.left = -50
    

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