ios - 使导航栏标题成为按钮(Swift)

标签 ios swift uinavigationcontroller uibutton titleview

我试图让导航栏的标题成为它自己的按钮。我的应用程序中的用户可以拥有多个个人资料,导航栏标题显示他们当前选择的个人资料的用户名。按下此按钮应该会弹出可供选择的可用配置文件列表 (handleShowProfiles)。出于某种原因,标题会显示但不能用作按钮,它只是静态文本并且触摸它不会执行任何操作。

let changeProfileContainer : UIView = {
    let container = UIView()
    container.frame = CGRect(x: 0, y: 0, width: 200, height: 40)

    let button = UIButton(type: .custom)
    button.setTitle("@username ▼", for: .normal)
    button.setTitleColor(.black, for: .normal)
    button.frame = container.frame
    button.addTarget(self, action: #selector(handleShowProfiles), for: .touchUpInside)

    container.addSubview(button)
    return container
}()

func configureNavBar() {
    self.navigationController?.navigationBar.tintColor = .black
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "send"), style: .plain, target: self, action: #selector(handleSubmitPost))
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "drafts"), style: .plain, target: self, action: #selector(handleDrafts))
    self.navigationItem.titleView = changeProfileContainer
}

知道为什么按钮部分不起作用吗?在 Apple 的文档中,它说您必须将按钮放在 View 中,自定义按钮类型,并更改按钮的默认框架 (0, 0, 0, 0)。我很确定这是我搞砸的地方,但我不知道。

最佳答案

链接到 self invocations in computed property -- 查看 Ahmad F 回答的最后一部分

不知道为什么,但是计算属性中的选择器似乎不起作用。

我尝试在不计算的情况下添加容器 View ,然后点击按钮就可以了。

func configureNavBar() {
    self.navigationController?.navigationBar.tintColor = .black
    let container = UIView()
    container.frame = CGRect(x: 0, y: 0, width: 200, height: 40)

    let button = UIButton(type: .custom)
    button.setTitle("@username ▼", for: .normal)
    button.setTitleColor(.black, for: .normal)
    button.frame = container.frame
    button.addTarget(self, action: #selector(pressTitle), for: .touchUpInside)
    container.addSubview(button)
    navigationItem.titleView = container
}

关于ios - 使导航栏标题成为按钮(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55231004/

相关文章:

ios - ObjC 未正确转发 scrollViewDidScroll 消息

objective-c - 使用自定义方法将自定义对象添加到数组 Swift 问题

iOS - 没有滑动背景图像的pushViewController

iphone - UINavigationController 在 UITabBarController 的 moreNavigationController 中不起作用

ios - iOS7 中的 UIVisualEffectView

ios - 在 iOS 中离线打开和存储加密文档

swift - 如何快速从 Firebase 中获取子项计数?

ios - 如何在 Swift 中获取硬件详细信息?

cocoa-touch - iPad表格 View 上的UISearchBar消失在导航 Controller 栏下方

iphone - 当我初始化自定义单元格时返回 'self' 而它没有设置为 '[(super or self) init...]' 的结果