Xcode Use PDF Image in Bar Button Item Size Too Big
Using Code what I do when the image size is too big, I resize the UIImage
before rendering/setting on the UIControl
. I have this extension on UIImage
that helps re-scale an image.
// MARK: - Used to scale UIImages
extension UIImage {
func scaleTo(_ newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? self
}
}
Using this would look like this
let defaultImage = UIImage(named: "someimagenamehere")?
.scaleTo(CGSize(width: 40, height: 40))
self.navigationItem.leftBarButtonItem = UIBarButtonItem(
image: defaultImage,
style: .plain,
target: self,
action: #selector(self.someselectorhere(_:)))
UPDATE: This is what it would look like using @IBDesignable and @IBInspectable
@IBDesignable
class CustomBarButtonItem: UIBarButtonItem {
@IBInspectable
var scaledHeight: CGFloat = 0 {
didSet {
self.image = self.image?.scaleTo(CGSize(width: self.scaledHeight, height: self.scaledWidth))
}
}
@IBInspectable
var scaledWidth: CGFloat = 0 {
didSet {
self.image = self.image?.scaleTo(CGSize(width: self.scaledHeight, height: self.scaledWidth))
}
}
}