如何将 UIButton 图片对齐到 UIButton 的右边缘?

8
如何将图像对齐到UIButton的右侧,以使其在所有设备上保持在右侧。下面的图像显示了一个带有图像(圆形三角形)的UIButton。该图像是iPhone 6的屏幕截图,它适合我想要的方式。但是对于iPhone 6+,图像向左移动了一点,对于iPhone 5,它向右移动,图像显示在UIButton之外。我知道这个原因,那就是我将UIEdgeInsets的左侧设置为300的值,这对于iPhone 6非常完美。所以我的问题是如何在所有iPhone上实现这种外观。谢谢。

enter image description here

我的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)



    }
}
2个回答

4
问题在于你硬编码了左侧插入:


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

显然,当你想要根据正确的位置进行配置时,这种方法行不通,无论按钮的宽度如何!如果由于自动布局或其他原因,按钮变得更宽或更窄,你的图片将停留在错误的位置。应该设置正确的缩进。 或者,子类化UIButton并覆盖imageRectForContentRect:。现在图像的位置将基于按钮的大小,无论大小如何(因为自动布局或其他原因)。

谢谢您的回答,@matt。但是我该如何使用imageRectForContentRect函数呢?我对Swift还不太熟悉。 - Loc Dai Le
4
我不会替你写代码。试试吧!实验一下!学习一下! - matt

0

iOS 15现在可以做到:

var configuration = UIButton.Configuration.plain()
configuration.title = "Close"
configuration.image = UIImage(named: "Arrow_Close")
// here
configuration.imagePlacement = .trailing

let button = UIButton(configuration: configuration, primaryAction: nil)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接