How to align an UIButton image on the right edge of the UIButton

How can I aligment an image to the right edge of an UIButton, so it will stay at the right edge for all devices. The image below shows and UIButton with an image (circle-triangle). The image is a screenshot from an iPhone 6 which fit like I want it to.But for iPhone 6+ the image is moves a little bit to the left and for an iPhone 5 it moves to the right and the image is show outside of the UIButton. I know the reason of this, it is because i set the UIEdgeInsets' left to be a value of 300 which fit perfect for an iPhone 6. So my question is how can I archieve this look for all iPhones. Thank you.

My code for the 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)



    }
}

The problem is that you are hard-coding the left inset:

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

Obviously that's not going to work when what you want to do is configure with respect to the right regardless of the width of the button! If the button gets wider or narrower because of auto layout or whatever, your image will be left hanging in the wrong place. Set the right inset instead.

Alternatively, subclass UIButton and override imageRectForContentRect: . Now the position of the image will be based on the button size, whatever it may be (because of auto layout or whatever).

链接地址: http://www.djcxy.com/p/30786.html

上一篇: 使用Spring Tool Suite STS以发布模式导出战争?

下一篇: 如何对齐UIButton右边的UIButton图像