如何以编程方式将图像添加/删除到Swift 3 / Xcode中的导航栏标题

时间:2017-03-30 17:56:51

标签: ios swift xcode swift3 uiimage

所以我目前在应用程序的左侧打开和关闭菜单栏,我想在打开菜单时在导航栏标题上显示某个图像。以下是我打开和关闭菜单的功能。

@IBAction func openMenu(_ sender: Any) {

    if (menuShowing) {
        self.navigationController?.navigationBar.barTintColor = UIColor(red:0.00, green:0.20, blue:0.63, alpha:1.0)
        navigationItem.leftBarButtonItem?.tintColor = UIColor.white
        navigationItem.titleView = ""
        leadingConstraint.constant = -240
        shadowLeadingConstraint.constant = -250
        UIView.animate(withDuration: 0.6, animations: {
            self.view.layoutIfNeeded()
        })

    }
    else {
        self.navigationController?.navigationBar.barTintColor = UIColor.white
        navigationItem.leftBarButtonItem?.tintColor = UIColor(red:0.00, green:0.20, blue:0.63, alpha:1.0)

        let image = UIImage(named: "MenuBarTransparent")
        navigationItem.titleView = UIImageView(image: image)
        navigationItem.titleView?.frame=CGRect(x:10, y:0, width:30, height:360)

        leadingConstraint.constant = 0
        shadowLeadingConstraint.constant = 0
        UIView.animate(withDuration: 0.3, animations: {
            self.view.layoutIfNeeded()
        })
    }
    menuShowing = !menuShowing
}

上述函数中的这部分代码会在我想要的时候显示图像,但是操纵x和y坐标没有任何效果,所以我无法正确地居中图像:

let image = UIImage(named: "MenuBarTransparent")
        navigationItem.titleView = UIImageView(image: image)
        navigationItem.titleView?.frame=CGRect(x:10, y:0, width:30,  height:360)

此外,每当我再次关闭菜单时,上面这部分代码都不允许我从导航栏标题中删除图像,它说"无法分配类型'字符串'输入' UIView?':

navigationItem.titleView = ""

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

以下是如何使用它的init设置对象的方法。

navigationItem.titleView = UIImageView.init(image:UIImage(名称:"图像"))

答案 1 :(得分:0)

您正在为标题视图指定字符串。我认为你应该使用navigationItem.titleView = ""而不是navigationItem.titleView = nil