Aligning image on right side of title on UIButton with imageEdgeInsets and titleEdgeInsets

I would like to add an image on the right side of the title something like this

|Button  [image]|
|title          |

And I am able to achieve this by this code

button.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0)
button.imageEdgeInsets = UIEdgeInsetsMake(0, 135, 0, 5)

But when the title is large, the title label and image intersect with each other. How can I break the title label?


This extension works for me:

Extension:

extension UIButton {
  func imageToRight() {
      transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
      titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
      imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
  }
}

Usage:

button.imageToRight()

enter image description here

Update for iOS 15

as described here: Meet the UIKit Button System

  1. Create your button configuration Choose from .plain(), .gray(), .tinted() or .filled()

    var config = UIButton.Configuration.filled()

  2. Choose the placement for your image Choose from all, top, bottom, trailing, leading, none

    config.imagePlacement = .trailing

  3. Assign the configuration to your button

    let myButton = UIButton(configuration: config, primaryAction: ...)


try this, it will never intersect title and image with each other. and i created a button in storyboard in centre. @IBOutlet weak var myButton: UIButton!

  let somespace: CGFloat = 10

  self.myButton.setImage(UIImage(named: "cross"), forState: UIControlState.Normal)

  self.myButton.imageEdgeInsets = UIEdgeInsetsMake(0, self.myButton.frame.size.width - somespace , 0, 0)

  print(self.myButton.imageView?.frame)

  self.myButton.titleEdgeInsets = UIEdgeInsetsMake(0, (self.myButton.imageView?.frame.width)! + somespace, 0, 10 )

enter image description here

and if you want multiline title for button change line break mode for button's title

self.myButton.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping

enter image description here

Swift 3.0

In swift 3.0 you can easily do it in interface builder.

Select the UIButton -> Attributes Inspector -> go to size inspector and modify the image or title insets. and if you want image on button's right side simply select the force Right-to-left in semantic view utilities

enter image description here.