如何将图像与 UIButton 的右边缘对齐,以便它在所有设备上都保持在右边缘。下图显示了带有图像(圆形-三角形)的 UIButton。该图像是 iPhone 6 的屏幕截图,符合我的要求。但对于 iPhone 6+,图像向左移动了一点,对于 iPhone 5,它向右移动,图像显示在用户界面按钮。我知道这是为什么,因为我将 UIEdgeInsets 的左值设置为 300,非常适合 iPhone 6。所以我的问题是如何为所有 iPhone 实现这种外观。谢谢。
我的 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)
}
}
最佳答案
问题是您正在对 left 插图进行硬编码:
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 300, bottom: 0, right: 0)
很明显,当您想做的是相对于 right 进行配置而不管按钮的宽度如何时,这显然是行不通的!如果按钮由于自动布局或其他原因而变宽或变窄,您的图像将卡在错误的位置。改为设置右侧插图。
或者,子类化 UIButton 并覆盖 imageRectForContentRect:
。现在图像的位置将基于按钮大小,无论它是什么(因为自动布局或其他原因)。
关于swift - 如何在 UIButton 的右边缘对齐 UIButton 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34001411/