Change position of UIBarButtonItem in UINavigationBar

后端 未结 20 1566
一个人的身影
一个人的身影 2020-11-27 10:31

How can I change the position of a UIBarButtonItem in a UINavigationBar? I would like my button to be about 5px higher than its normal position.

20条回答
  •  天涯浪人
    2020-11-27 11:23

    Here's Adriano's solution using Swift 3. It was the only solution that worked for me and I tried several.

      let suggestImage  = UIImage(named: "menu.png")!
        let suggestButton = UIButton(frame: CGRect(x:0, y:0, width:34, height:20))
        suggestButton.setBackgroundImage(suggestImage, for: .normal)
        suggestButton.addTarget(self, action: #selector(self.showPopover(sender:)), for:.touchUpInside)
        suggestButton.transform = CGAffineTransform(translationX: 0, y: -8)
        // add the button to a container, otherwise the transform will be ignored
        let suggestButtonContainer = UIView(frame: suggestButton.frame)
        suggestButtonContainer.addSubview(suggestButton)
        let suggestButtonItem = UIBarButtonItem(customView: suggestButtonContainer)
        // add button shift to the side
        navigationItem.leftBarButtonItem = suggestButtonItem
    

提交回复
热议问题