简体   繁体   中英

Different title origin of UIButton with image inside in different iOS versions

  • I created a button in interface builder.
  • Set fixed width = 120 and height = 40 constraints to this button.
  • After I add an image to button and set image insets (top: 10, left: 0, bottom: 10, right: 100) to move the image to the left side.

UIButton insets screenshot

The problem: In different iOS versions (in my case it's: 10.3.1, 12.1 and 13.1) the button drawing differently. Button's title origin is (x = 29.5, y = 11) for iOS 13.1 and (x = 44, y = 11) for older iOS.

Simulators screenshot

How to make buttons look identical in all iOS versions?

i know what you're trying to do and just don't. it's going to crush you trying to do this as you think it should work. instead do this

  1. make your button as you did above
  2. add a UIImageView to the button, so the UIimageView is added as a subview to the UIButton
  3. add the constraints on the UIImageView so that the image view is on the very left side of the button

this is how you hack around with iOS to make things work that should work but don't, and without needing to subclass the UIButton and do some crazy geometry math's with it's own inner imageview.

My research revealed a possible reason for such a different drawing of buttons. And the reason is imageView's old frame. After adding image insets to move image to left / right, the image frame changes. I don't know how exactly Apple calculates title's origin of button. In older iOS title's origin.x is equal image's old frame.width. In iOS 13 title's origin changes as I expected.

So i decided to resize an UIImage before I put it into UIImageView. And it works pretty well.

Thanks to everyone who gave advice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM