在Swift中垂直居中backIndicatorImage

时间:2015-04-04 11:06:07

标签: swift uinavigationbar

我已使用以下代码将自定义图片放入backIndicatorImage

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

图像略高于标准图形,因此我希望能够垂直居中。

我尝试使用此代码在导航栏中找到图像(不是很优雅)(欢迎任何更好的建议):

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
    }
}

令人沮丧的是,图像暂时出现在正确的位置,然后被放回原来的位置。

我试过这样说:

  • viewDidLoad中
  • viewWillLayoutSubviews
  • viewDidLayoutSubviews
  • viewDidAppear

没有快乐。

有人有任何建议吗?

1 个答案:

答案 0 :(得分:5)

您可以通过下一个代码直接更改您的UIImage 位置。 您可以手动设置原点:

...
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
}