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

标签 swift uibutton uiimage xcode7

如何将图像与 UIButton 的右边缘对齐,以便它在所有设备上都保持在右边缘。下图显示了带有图像(圆形-三角形)的 UIButton。该图像是 iPhone 6 的屏幕截图,符合我的要求。但对于 iPhone 6+,图像向左移动了一点,对于 iPhone 5,它向右移动,图像显示在用户界面按钮。我知道这是为什么,因为我将 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)



    }
}

最佳答案

问题是您正在对 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/

相关文章:

ios - 在按钮边缘绘制框架

ios - 如何从 IOS 中的元数据中获取图像显示为任何网站的预览

swift - 当文本字段中有整数时按钮不启用/禁用

带有用于切换的容器 View 的 iOS Swift 分段控件 - View 不是第一次加载

ios - 一秒钟后 UIButton 退出突出显示模式

swift - 为 uibutton Swift 的背景图像分配 "aspect fill"选项

iphone - NSData 空检查

ios - 如何使用 ex 更改 UIImageView 的图像。 [触摸 View ]

arrays - Swift removeSubrange 足够快吗?

ios - Swift NSDictionary 子类型