代码之家  ›  专栏  ›  技术社区  ›  Enrique

以编程方式构建工具栏

  •  1
  • Enrique  · 技术社区  · 7 年前

    UITableViewController ,所以我正在努力以编程方式添加它。

    这就是我想让它看起来的样子:

    iOS screenshot

    现在,我添加了以下代码:

        let homeButton = UIBarButtonItem(title: "H", style: .plain, target: self, action: #selector(ProfileButtonTapped))
    
        let addButton = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(ProfileButtonTapped))
    
    let loveButton = UIBarButtonItem(title: "Love", style: .plain, target: self, action: #selector(ProfileButtonTapped))
    
    let arr: [Any] = [homeButton, addButton, loveButton]
    setToolbarItems(arr as? [UIBarButtonItem] ?? [UIBarButtonItem](), animated: true)
    super.viewDidAppear(animated)
    

    看起来是这样的:

    iOS screenshot

    我试着使用我在这里找到的代码,看起来很有效,但当我加载我的应用程序时,它只是显示没有任何元素的条。

    navigationController?.setToolbarHidden(false, animated: true)
    
    let homeButn = UIImage(named: "HomeButton")
    
    let zeroPoint = CGPoint.zero
    let settingsButton = UIButton(type: UIButtonType.custom) as UIButton
    settingsButton.frame = CGRect(origin: zeroPoint, size: CGSize(width: 27, height: 27))
    settingsButton.setImage(homeButn, for: [])
    settingsButton.addTarget(self, action: #selector(ProfileButtonTapped), for: UIControlEvents.touchUpInside)
    
    let rightBarButtonItem = UIBarButtonItem(customView: settingsButton)
    navigationItem.setRightBarButton(rightBarButtonItem, animated: true)
    

    1 回复  |  直到 7 年前
        1
  •  2
  •   Amit    7 年前

    如果有帮助,请尝试以下方法:

    let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
    
    let homeButton = UIBarButtonItem(title: "H", style: .plain, target: self, action: #selector(ProfileButtonTapped))
    
    let flexibleSpace1 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
    
    let addButton = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(ProfileButtonTapped))
    
    let flexibleSpace2 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
    
    let loveButton = UIBarButtonItem(title: "Love", style: .plain, target: self, action: #selector(ProfileButtonTapped))
    
    let arr: [Any] = [flexibleSpace, homeButton, flexibleSpace1, addButton, flexibleSpace2, loveButton]
    
    setToolbarItems(arr as? [UIBarButtonItem] ?? [UIBarButtonItem](), animated: true)
    
    super.viewDidAppear(animated)
    

    您也可以在“H”的左侧添加灵活的空间,以获得剩余空间。