How to align a UIButton image to the right edge of a UIButton

How can I transfer the image to the right edge of UIButton so that it remains on the right edge for all devices. The image below shows the UIButton with the image (circle-triangle). The image is a screenshot from the iPhone 6, which, like me, fits it. But for iPhone 6+, the image moves slightly to the left, and for iPhone 5 it moves to the right, and the image is displayed outside of UIButton. I know the reason for this because I found that UIEdgeInsets remained at 300, which is perfect for iPhone 6. So my question is how can I archive this view for all iPhones. Thanks.

enter image description here

My code for UIButton:

class DropDownButton : UIButton{ required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! style() } private func style() { self.titleEdgeInsets.left = 0 self.layer.cornerRadius = 2; self.setImage(UIImage(named: "Arrow_Close"), forState: UIControlState.Normal) self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 300, bottom: 0, right: 0) self.backgroundColor = UIColor(CGColor: "#FFFFFF".CGColor) self.tintColor = UIColor(CGColor: "#616366".CGColor) self.titleLabel!.font = UIFont(name: "OpenSans", size: 15) } } 
+7
swift xcode7 uibutton uiimage
source share
1 answer

The problem is that you hardcode the left insert:

 self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 300, bottom: 0, right: 0) 

Obviously, it won’t work when what you want to do is set to the correct one regardless of the width of the button! If the button gets wider or narrower due to automatic layout or something else, your image will remain hanging in the wrong place. Instead, set the correct insert.

Alternatively, subclass UIButton and override imageRectForContentRect: Now the position of the image will be based on the size of the button, whatever it may be (due to automatic layout or something else).

+3
source share

All Articles