Swift如何改变backIndicatorImage的位置和大小

时间:2017-08-08 11:53:29

标签: swift

我的AppDelegate中有这段代码

UINavigationBar.appearance().backIndicatorImage = #imageLiteral(resourceName: "backarrow")

此代码显示类似

的内容

enter image description here

如何调整大小并更改图像的位置?

3 个答案:

答案 0 :(得分:2)

您好,您可以通过以下方式实施: -

var backImage = UIImage(named: "backarrow")     
backImage = resizeImage(image: backImage!, newWidth: 40) //the width that you want for the back button image
UINavigationBar.appearance().backIndicatorImage = backImage

这是图像调整大小功能

func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage? {

    let scale = newWidth / image.size.width
    let newHeight = image.size.height * scale
    UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
    image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

答案 1 :(得分:0)

您必须通过自定义按钮更改按钮。 定义UIBarButtonItem并使用自定义按钮替换默认值。

var customButton =  UIBarButtonItem(image: closeButtonImage, style: .plain, target: self, action:  #selector(YourController.backPressed(_:)))
self.navigationItem. backBarButtonItem = customButton

答案 2 :(得分:0)

只需使用自定义UIBarButtonItem并隐藏默认值即可。

    let backButton = UIBarButtonItem(image: UIImage(named: "Your_Back_Button_Image", style: .plain, target: self, action: #selector(popCurrentViewController)
    self.navigationItem.setHidesBackButton(true, animated: true)
    self.navigationItem.leftBarButtonItem = backButton

实现后退功能:

func popCurrentViewController(_ animated: Bool)
{
    _ = self.navigationController?.popViewController(animated: true)
}