How to post images and text in UIButton

Asked 2 years ago, Updated 2 years ago, 107 views

I use the original image in UIButton to create a custom button, but I can't put the image and text together.Buttons only display images.How can I display the text on the button?Thank you for your cooperation.Also, I don't use the storyboard for convenience, so I would appreciate it if you could tell me how to improve it with the code.

let buttonImageDefault: UIImage?= UIImage(named: "btn_default") // Button image
let buttonImageSelected: UIImage?= UIImage(named: "btn_selected") // Button image when pressed


let exitButton=UIButton(type:UIButtonType.Custom)
exitButton.frame = CGRect(x:board.bounds.midX-buttonImageDefault!.size.width/2, ,
                          y:board.bounds.midY-buttonImageDefault!.size.height/2,
                          width —ButtonImageDefault!.size.width,
                          height —ButtonImageDefault!.size.height)

exitButton.setImage(buttonImageDefault!, forState:UIControlState.Normal)
exitButton.setImage(buttonImageSelected!, forState:UIControlState.Highlighted)
exitButton.setTitleColor(UIColor.blackColor(), forState: .Normal)// The text is black because the button is white
exitButton.setTitle("Finish", forState:.Normal)

swift ios iphone uikit

2022-09-30 21:18

1 Answers

I have to answer by myself, but I have corrected it, so I will put it on the list.After adding the bottom line of titleEdgeInsets, I was able to correct the character position.Perhaps the text existed, but it didn't look bad.If you know why the text is misaligned, please let me know.Also, please let me know if there are any other ways to improve it.

let buttonImageDefault: UIImage?= UIImage(named: "btn_default") // Button image
let buttonImageSelected: UIImage?= UIImage(named: "btn_selected") // Button image when pressed

let exitButton=UIButton(type:UIButtonType.Custom)
exitButton.frame = CGRect(x:board.bounds.midX-buttonImageDefault!.size.width/2, ,
                      y:board.bounds.midY-buttonImageDefault!.size.height/2,
                      width —ButtonImageDefault!.size.width,
                      height —ButtonImageDefault!.size.height)

exitButton.setImage(buttonImageDefault!, forState:UIControlState.Normal)
exitButton.setImage(buttonImageSelected!, forState:UIControlState.Highlighted)
exitButton.setTitleColor(UIColor.blackColor(), forState: .Normal)// The text is black because the button is white
exitButton.setTitle("Finish", forState:.Normal)

// This part

exitButton.titleEdgeInsets=UIEdgeInsetsMake (0.0,-board.bounds.midX+exitButton.bounds.midX,0,0)


2022-09-30 21:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.