Change position of UIBarButtonItem in UINavigationBar

后端 未结 20 1564
一个人的身影
一个人的身影 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:08

    I solved using transform and custom view:

    (Swift)

      // create the button
      let suggestImage  = UIImage(named: "tab-item-popcorn-on")!.imageWithRenderingMode(.AlwaysOriginal)
      let suggestButton = UIButton(frame: CGRectMake(0, 0, 40, 40))
      suggestButton.setBackgroundImage(suggestImage, forState: .Normal)
      suggestButton.addTarget(self, action: Selector("suggesMovie:"), forControlEvents:.TouchUpInside)
    
      // here where the magic happens, you can shift it where you like
      suggestButton.transform = CGAffineTransformMakeTranslation(10, 0)
    
      // 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.rightBarButtonItem = suggestButtonItem
    

提交回复
热议问题