iosuser-interfacelayoutuibutton

How do I put the image on the right side of the text in a UIButton?


I don't want to use a subview if I can avoid it. I want a UIButton with a background image, text, and an image in it. Right now, when I do that, the image is on the left side of the text. The background image, text, and image all have different highlight states.


Solution

  • Despite some of the suggested answers being very creative and extremely clever, the simplest solution is as follows:

    button.semanticContentAttribute = UIApplication.shared
        .userInterfaceLayoutDirection == .rightToLeft ? .forceLeftToRight : .forceRightToLeft
    

    As simple as that. As a bonus, the image will be at the left side in right-to-left locales.

    EDIT: as the question has been asked a few times, this is iOS 9 +.