Wernzy
Wernzy

Reputation: 1098

UIButton with title and image, system selected background doesn't include image

I've got a UIButton of type .system that I am creating programmatically with Swift 4. It has a title and an image, and I'm toggling isSelected on and off on touch. When I toggle it on, there is a lovely coloured background added around the title of the image, but it doesn't extend far enough to include the image. These pictures explain far better than I can:

Unselected Selected

Is there any way to get that background to extend further over so the icon is a part of it? I don't mind changing the colour of the icon manually, but everything I've tried (titleEdgeInsets, contentEdgeInsets) has just moved the title and background around without actually extending it.

I would prefer to keep the button a .system button rather than a .custom one, and I like that the frame of the button (and therefore the touch area) is larger than that coloured background because it makes it easier to touch, I imagine if I was setting a solid colour backgroundImage to emulate the effect I would have to decrease the touch area to match, which I don't want.

Any help would be most appreciated! Thanks in advance!

Edit: I've added an image with button.layer.borderWidth = 1 to show the actual frame of the button, and how it differs from the isSelected background which appears around the title. (The gray is because it's in a grouped tableView)

enter image description here

Upvotes: 4

Views: 631

Answers (2)

Yifan Zhang
Yifan Zhang

Reputation: 1

If you use SF symbols, you can make the image part of the titleLabel:

let attachment = NSTextAttachment()
attachment.image = UIImage(systemName: "checkmark.circle")

let imageString = NSMutableAttributedString(attachment: attachment)
let textString = NSAttributedString(string: "Please try again")
imageString.append(textString)

Then set imageString to UIButton.attributedTitle.

https://www.hackingwithswift.com/articles/237/complete-guide-to-sf-symbols

Haven't tested with custom images.

Upvotes: 0

Procrastin8
Procrastin8

Reputation: 4503

The short answer is a .system button really only expects either an image or a title, not both. (See this for a more comprehensive matrix highlighting your issue)

There isn't really anything special about the .system button for your case, though. Create a .custom button and round button.layer.cornerRadius to get the corner effect.

Upvotes: 1

Related Questions