Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Replaced back button too close to edge

Tags:

ios

swift

I want to globally change the navigation bar back button, so I have this:

UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(-100, -5000), forBarMetrics: .Default)
        var backImage: UIImage = UIImage(named: "BackButton")!
        backImage = backImage.imageWithAlignmentRectInsets(UIEdgeInsetsMake(0, 0, 0, 20))
        UINavigationBar.appearance().backIndicatorImage = backImage
        UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage

But the back image is too close to the left of the screen. How do I move it farther to the right?

enter image description here

like image 210
Stefan Kendall Avatar asked Sep 13 '15 19:09

Stefan Kendall


2 Answers

Just adjust the actual image.

extension UIImage {
    func imageWithInsets(insets: UIEdgeInsets) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(
        CGSizeMake(self.size.width + insets.left + insets.right,
                self.size.height + insets.top + insets.bottom), false, self.scale)
        let context = UIGraphicsGetCurrentContext()
        let origin = CGPoint(x: insets.left, y: insets.top)
        self.drawAtPoint(origin)
        let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return imageWithInsets
    }
}

For Swift 4:

extension UIImage {
    func withInsets(_ insets: UIEdgeInsets) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(
            CGSize(width: size.width + insets.left + insets.right,
                   height: size.height + insets.top + insets.bottom),
            false,
            self.scale)

        let origin = CGPoint(x: insets.left, y: insets.top)
        self.draw(at: origin)
        let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return imageWithInsets
    }
}
like image 137
Stefan Kendall Avatar answered Oct 01 '22 03:10

Stefan Kendall


You need to adjust the left position on UIEdgeInsetsMake.

You are already calling it here:

backImage = backImage.imageWithAlignmentRectInsets(UIEdgeInsetsMake(0, 0, 0, 20))

Like so:

backImage = backImage.imageWithAlignmentRectInsets(UIEdgeInsetsMake(0, -50, 0, 50))
like image 28
CaptJak Avatar answered Oct 01 '22 03:10

CaptJak