【问题标题】:Adding subview to navigation bar with a search controller使用搜索控制器将子视图添加到导航栏
【发布时间】:2020-07-31 11:19:11
【问题描述】:

我正在尝试向导航栏添加自定义子视图按钮,但无法将其放置在所需位置。我的目标是让按钮以标题标签为中心,无论它是大还是小。但现在我正试图将它锚定到导航栏的底部。但是,我无法访问搜索栏来正确添加约束。

Current Outcome

func setupNav() {
    guard let navController = navigationController else { return }
    let navBar = navController.navigationBar

    let settingsButton = UIButton()
    settingsButton.setImage(UIImage(named: "settings-button")?.withRenderingMode(.alwaysTemplate), for: .normal)
    settingsButton.tintColor = .textColor()
    settingsButton.addTarget(self, action: #selector(openSettings), for: .touchUpInside)

    navBar.addSubview(settingsButton)
    settingsButton.anchor(top: nil, left: nil, bottom: navBar.bottomAnchor, right: navBar.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 5, paddingRight: 10, width: 30, height: 30)
}

【问题讨论】:

    标签: ios swift xcode uinavigationcontroller


    【解决方案1】:

    您应该可以通过使用访问搜索栏

    navigationItem.searchController?.searchBar
    

    【讨论】:

      【解决方案2】:

      您需要设置按钮的此属性,以便以编程方式添加约束:

      settingsButton.translatesAutoresizingMaskIntoConstraints = false

      这是我的代码:

      func setupNav() {
          guard let navController = navigationController else { return }
          let navBar = navController.navigationBar
      
          let button = UIButton()
          button.setTitle("Test", for: .normal)
          button.setTitleColor(.red, for: .normal)
          button.translatesAutoresizingMaskIntoConstraints = false
      
          button.addTarget(self, action: #selector(openSettings), for: .touchUpInside)
      
          navBar.addSubview(button)
          navBar.addConstraints([
              NSLayoutConstraint(item: navBar, attribute: .trailing, relatedBy: .equal, toItem: button, attribute: .trailing, multiplier: 1, constant: 20),
              NSLayoutConstraint(item: button, attribute: .centerY, relatedBy: .equal, toItem: navBar, attribute: .centerY, multiplier: 1, constant: 0)
          ])
      }
      

      编码愉快。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多