可点击的图像作为Swift中的导航栏标题

时间:2018-10-29 04:44:26

标签: ios swift uinavigationcontroller uibutton uinavigationbar

我在这里浏览了多个讨论主题:

  1. 设置标题图像
  2. 使用标题按钮

但是,我试图将两者结合起来,即将可点击的图像(按钮)作为标题。

不幸的是,虽然下面的代码编译了图像,但将其分配为按钮时未显示。有什么建议吗?

func addNavBarImage() {
    let navController = navigationController!

    let button =  UIButton(type: .custom)
    var image = UIImage(named: "textLogo")
    image = image?.withRenderingMode(.alwaysOriginal)

    let bannerWidth = navController.navigationBar.frame.size.width
    let bannerHeight = navController.navigationBar.frame.size.height

    let bannerX = bannerWidth / 2 - image!.size.width  / 2
    let bannerY = bannerHeight / 2 - image!.size.height / 2

    button.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
    button.imageView?.contentMode = .scaleAspectFit
    button.imageView?.image = image

    button.addTarget(self, action: #selector(self.logoTapped), for: .touchUpInside)
    self.navigationItem.titleView = button
}

2 个答案:

答案 0 :(得分:0)

创建.map(JsonElement::getAsJsonObject) .forEach(jsonObject -> custom.add(new MyClass( ... jsonObject.has("stuff4")? jsonObject.get("stuff4").getAsInt():null))); ,将其添加为titleView并将UIImageView添加到您的UITapGestureRecognizer

UIImageView

答案 1 :(得分:0)

为我工作的代码。

let button =  UIButton(type: .custom)
button.setImage(UIImage (named: "your_image"), for: .normal)
button.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
button.backgroundColor = UIColor.clear
button.setTitle("Button", for: .normal)
button.addTarget(self, action: #selector(self.clickOnButton), for: .touchUpInside)
self.navigationItem.titleView = button

在这里您可以看到最后一行中的按钮直接设置为navigationItem的titleView,它将在导航栏的中央添加按钮。

按钮的操作方法如下:

@objc func clickOnButton(button: UIButton) {
    print("Title Tapped")
}
相关问题