Change position of UIBarButtonItem in UINavigationBar

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

    Try the code below,

    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"Logout" style:UIBarButtonItemStyleDone target:self action:nil];
    [button setBackgroundVerticalPositionAdjustment:-20.0f forBarMetrics:UIBarMetricsDefault];
    [[self navigationItem] setRightBarButtonItem:button];
    

    Its used to change the 'y' position in this code. Change the 'y' value (here it is -20.0f) according to your requirement. If the value is positive, it will down the button position. If the value is negative, it will up your button position.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题