对于 Swift 4.0,这是一个有效的扩展 -
extension UIButton {
func leftImage(image: UIImage, renderMode: UIImage.RenderingMode) {
self.setImage(image.withRenderingMode(renderMode), for: .normal)
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
self.titleEdgeInsets.left = (self.frame.width/2) - (self.titleLabel?.frame.width ?? 0)
self.contentHorizontalAlignment = .left
self.imageView?.contentMode = .scaleAspectFit
}
func rightImage(image: UIImage, renderMode: UIImageRenderingMode){
self.setImage(image.withRenderingMode(renderMode), for: .normal)
self.imageEdgeInsets = UIEdgeInsets(top: 0, left:image.size.width / 2, bottom: 0, right: 0)
self.contentHorizontalAlignment = .right
self.imageView?.contentMode = .scaleAspectFit
}
}
用法:
myButton.rightImage(image: UIImage(named: "image_name")!, renderMode: .alwaysOriginal)
myButton.leftImage(image: UIImage(named: "image_name")!, renderMode: .alwaysOriginal)
renderMode
可以是.alwaysTemplate
或.alwaysOriginal
。另外,myButton
应该是custom
type UIButton
。
这个扩展的leftImage
andrightImage
也可以UIButton
在UIBarButtonItem
for中使用UINavigationBar
(注意:从 iOS 11 开始,导航栏遵循自动布局,因此您需要在 中添加宽度/高度约束UIBarButtonItem
)。要在导航栏上使用,请确保遵循 Apple 推荐的 @2x 和 @3x 图像尺寸(即 50x50、75x75)并在 iPhone 6、7、8、6s、7s、8s、Plus 变体和 iPhone 上获得更好的可访问性x 的宽度和高度UIBarButton
可以是高度 - 25 和宽度 - 55(或者无论您的应用程序需要什么,这些数字都是一些基本数字,应该适用于大多数情况)。
更新:在 Swift 4.2 中,UIImageRenderingMode
已重命名为UIImage.RenderingMode
extension UIButton {
func leftImage(image: UIImage, renderMode: UIImage.RenderingMode) {
self.setImage(image.withRenderingMode(renderMode), for: .normal)
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: image.size.width / 2)
self.contentHorizontalAlignment = .left
self.imageView?.contentMode = .scaleAspectFit
}
func rightImage(image: UIImage, renderMode: UIImage.RenderingMode){
self.setImage(image.withRenderingMode(renderMode), for: .normal)
self.imageEdgeInsets = UIEdgeInsets(top: 0, left:image.size.width / 2, bottom: 0, right: 0)
self.contentHorizontalAlignment = .right
self.imageView?.contentMode = .scaleAspectFit
}
}