swift – 如何在UIButton的右边缘对齐UIButton图像

前端之家收集整理的这篇文章主要介绍了swift – 如何在UIButton的右边缘对齐UIButton图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何将图像对齐到UIButton的右边缘,因此它将保留在所有设备的右边缘.下图显示了带有图像的UIButton(圆三角形).图像是来自iPhone 6的屏幕截图,它符合我的要求.但是对于iPhone 6,图像向左移动一点,对于iPhone 5,它向右移动,图像显示在UIButton之外.我知道这个的原因,这是因为我将UIEdgeInsets的左边设置为300适合iPhone 6的值.所以我的问题是我如何能够为所有iPhone设置这种外观.谢谢.

我的UIButton代码

  1. class DropDownButton : UIButton{
  2.  
  3. required init(coder aDecoder: NSCoder) {
  4. super.init(coder: aDecoder)!
  5. style()
  6. }
  7.  
  8. private func style() {
  9. self.titleEdgeInsets.left = 0
  10. self.layer.cornerRadius = 2;
  11. self.setImage(UIImage(named: "Arrow_Close"),forState: UIControlState.Normal)
  12. self.imageEdgeInsets = UIEdgeInsets(top: 0,left: 300,bottom: 0,right: 0)
  13. self.backgroundColor = UIColor(CGColor: "#FFFFFF".CGColor)
  14. self.tintColor = UIColor(CGColor: "#616366".CGColor)
  15. self.titleLabel!.font = UIFont(name: "OpenSans",size: 15)
  16.  
  17.  
  18.  
  19. }
  20. }
问题是你是硬编码左边插图:
  1. self.imageEdgeInsets = UIEdgeInsets(top: 0,right: 0)

显然,无论按钮的宽度如何,当您想要做的是相对于右侧进行配置时,它将无法工作!如果由于自动布局或其他原因按钮变宽或变窄,您的图像将被悬挂在错误的位置.改为设置正确的插图.

或者,子类UIButton并覆盖imageRectForContentRect:.现在,图像的位置将基于按钮大小,无论它是什么(因为自动布局或其他).

猜你在找的Swift相关文章