1

我正在尝试使导航栏的标题成为自己的按钮。我的应用程序中的用户可以有多个配置文件,导航栏标题显示他们当前选择的配置文件的用户名。按下此按钮应显示可供选择的可用配置文件列表(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 的文档中,它说您必须将按钮放在视图中,自定义按钮类型,并将按钮的框架从默认值 (0, 0, 0, 0) 更改。我很确定这是我搞砸的地方,但我不知道。

4

1 回答 1

1

链接到计算属性中的自我调用- 请参阅 Ahmad F 答案的最后一部分

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

我尝试添加容器视图而不计算它并单击按钮有效。

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
}
于 2019-03-18T23:06:07.350 回答