Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode Use PDF Image in Bar Button Item Size Too Big

I have a PDF file in my image assets file in my Xcode project. I'm trying to create a bar button item that uses that PDF image. But whenever I set the image property in Interface Builder to the image it takes over most of my tab bar and removes the title.

I have a left bar button item with the system item stop. So it looks like an X icon. I would like to do the same thing on the right side with my settings PDF image I have.

Is there a way to fix this sizing issue within Interface Builder? If not how can I fix this in code?

like image 949
Charlie Fish Avatar asked Oct 10 '17 22:10

Charlie Fish


1 Answers

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))
        }
    }
}
like image 181
Zonily Jame Avatar answered Sep 29 '22 08:09

Zonily Jame