4

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

Wernzy
  • 1,088
  • 8
  • 22
  • My best guess? A `UIButton` image is separate from the `titleLabel`. I what you have is accurate that is. Maybe you could try a few things. (1) Have *two* images - one for `normal` and one for `isSelected`. (2) Subclass `UIButton` and instead of using it's canned image, add your own `UIImageView` with a clear background. Finally, (3) Roll your own `UIButton` complete with tap gestures. –  Dec 07 '18 at 18:55

2 Answers2

1

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.

Procrastin8
  • 4,193
  • 12
  • 25
0

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.