Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically center backIndicatorImage in Swift

I have put a custom image into the backIndicatorImage using this code:

var backButton = UIImage(named: "locationbar_back")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
self.navigationController!.navigationBar.backIndicatorImage = backButton
self.navigationController!.navigationBar.backIndicatorTransitionMaskImage = backButton

The image is slightly taller than the standard graphic so I want to be able to vertically center it.

I have tried finding the image in the navbar (not very elegantly) using this code (any better suggestions welcome):

for myview in self.navigationController!.navigationBar.subviews as [UIView]
{
    if myview.frame.width == 17 //need a better way of identifying object
    {
        var newFrame = myview.frame
        newFrame.origin.y = 6.0
        myview.frame = newFrame
    }
}

The frustrating thing is that the image appears momentarily in the right place and then gets put back to its original position.

I have tried calling this in :

  • viewDidLoad
  • viewWillLayoutSubviews
  • viewDidLayoutSubviews
  • viewDidAppear

with no joy.

Does any one have any suggestions please?

like image 981
iphaaw Avatar asked Apr 04 '15 11:04

iphaaw


1 Answers

You can change your UIImage position directly by next code. Origin you can set manually:

...
var backButtonImage = UIImage(named: "backButtonImage")!
backButtonImage = changeImagePosition(backButtonImage, origin: CGPointMake(0, 0))

navigationController!.navigationBar.backIndicatorImage = backButtonImage
navigationController!.navigationBar.backIndicatorTransitionMaskImage = backButtonImage
...
func changeImagePosition(image: UIImage, origin: CGPoint) -> UIImage {
    let size = image.size

    UIGraphicsBeginImageContextWithOptions(size, false, 2)
    image.drawInRect(CGRectMake(origin.x, origin.y, size.width, size.height))

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}
like image 94
dimpiax Avatar answered Sep 27 '22 23:09

dimpiax