Next Button 就像 Navigation 的 Back Button

Next Button like Navigation's Back Button

我想像后退按钮一样显示下一个按钮,但 rightBarButton 不像后退栏按钮那样触及屏幕末尾。

        let button = UIButton(type: .system)
        button.setImage(UIImage(named: "ic_next_button"), for: .normal) // 22x22 1x, 44x44 2x, 66x66 3x
        button.setTitle("Next", for: .normal)
        button.sizeToFit()
        button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
        button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
        button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)

创建另一个 UIBarButtonItem,类型为 .fixedSpace,宽度为负值。然后将两个按钮添加为右栏按钮项。

      let button = UIButton(type: .system)
      button.setImage(UIImage(named: "right"), for: .normal) // 22x22 1x, 44x44 2x, 66x66 3x
      button.setTitle("Next", for: .normal)
      button.sizeToFit()
      button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
      button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
      button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
      let nextBtn = UIBarButtonItem(customView: button)
      let spaceBtn = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
      spaceBtn.width = -8// Change this value as per your need
      self.navigationItem.rightBarButtonItems = [spaceBtn, nextBtn];

正如前面的答案所指出的,你需要做的就是在你的nextButton左边添加一个负固定space,它会被推到右边。

这段代码创建了一个 8 点的负固定宽度(这对你的情况来说似乎足够了,但你可以根据需要随意调整):

let negativeWidthButtonItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, 
                                              target: nil, 
                                              action: nil)
negativeWidthButtonItem.width = -8

创建此按钮后,将其添加到 rightBarButtonItems 数组中:

self.navigationItem.rightBarButtonItems = [negativeWidthButtonItem, nextButton]

Whosebug 上的一些其他答案也引用了相同的解决方案:

  • reduce left space and right space from navigation bar left and right bar button item

  • How to Edit Empty Spaces of Left, Right UIBarButtonItem in UINavigationBar [iOS 7]

UIBarButtonSystemItem.fixedSpace会占用BarButtonItem前多出来的space。

    let button = UIButton(type: .system)
    button.setImage(UIImage(named: "ic_next_button"), for: .normal) // 22x22 1x, 44x44 2x, 66x66 3x
    button.setTitle("Next", for: .normal)
    button.sizeToFit()
    button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
    button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
    button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)

    let rightBarButton = UIBarButtonItem()
    rightBarButton.customView = button

    let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
    negativeSpacer.width = -25;

    self.navigationItem.setRightBarButtonItems([negativeSpacer, rightBarButton ], animated: false)