Xcode Using a PDF Image in a Button Bar Element Size Too Large

I have a PDF file in my image file in my Xcode project. I am trying to create a panel button element that uses this PDF image. But whenever I set an image property in Interface Builder for an image, it takes most of my tab bar and removes the title.

I have an element with the left button of the panel with a stop of the system element. Thus, it looks like an X icon. I would like to do the same on the right side with my settings. I have a pdf image.

Is there a way to fix this dimension problem in Interface Builder? If not, how can I fix this in code?

+11
source share
1 answer

Using the code, what I do when the image size is too large, I UIImage size of the UIImage before rendering / settings in UIControl . I have this extension on UIImage which helps to scale the 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 it will 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)) } } } 
+10
source

Source: https://habr.com/ru/post/1272516/


All Articles