navigation bar right bar button items spacing

前端 未结 10 2166
执念已碎
执念已碎 2021-01-31 16:47

I have created a with left bar button item added from storyboard, titleView and three right bar button items from code.

Here is the code:

override func         


        
10条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-31 17:17

    Supporting solution by @mkz, by using function to reduce the code (Swift 4.2.1)

    Added most important parameters to the function (note how to pass selector to a function), you may want to add more as per your need.

    func makeCustomNavigationButton(imageName: String, action: Selector) -> UIBarButtonItem{
    
        let image = UIImage(named: imageName)!
        let btn: UIButton = UIButton(type: UIButton.ButtonType.custom)
        btn.setImage(image, for: .normal)
        btn.addTarget(self, action: action, for: .touchUpInside)
        btn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        let barBtn = UIBarButtonItem(customView: btn)
    
        return barBtn
    }
    

    How to call:

    let search = self.makeCustomNavigationButton(imageName: "search", action: #selector(searchBtnPressed(_:)))
    let clip = self.makeCustomNavigationButton(imageName: "clip", action: #selector(clipBtnPressed(_:)))
    let pencil = self.makeCustomNavigationButton(imageName: "pencil", action: #selector(pencilBtnPressed(_:)))
    self.navigationItem.rightBarButtonItems = [search, clip, pencil]
    

提交回复
热议问题