iOS 11上导航栏中UIBarButtonItem的负间隔

pck*_*ill 24 objective-c ios uistackview ios11

在iOS 10及更低版本中,有一种方法可以在导航栏中的按钮数组中添加负间隔,如下所示:

UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
negativeSpacer.width = -8;
self.navigationItem.leftBarButtonItems = @[negativeSpacer, [self backButtonItem]];
Run Code Online (Sandbox Code Playgroud)

这不再适用于iOS 11(间隔变为正,而不是负).我已经检查了条形按钮项的视图层次结构,现在它已嵌入到_UIButtonBarStackView.如何在iOS 11上调整条形按钮的位置?

kei*_*ter 12

我在Apple开发者论坛上找到了一个有点讨厌的解决方案:https: //forums.developer.apple.com/thread/80075

看起来问题来自于iOS 11如何处理UIBarButtonItem .fixedSpace按钮以及如何UINavigationBar在iOS 11中布局.导航栏现在使用自动布局和布局边距来布局按钮.该帖子(底部)中提供的解决方案是将所有布局边距设置为您想要的某个值.

class InsetButtonsNavigationBar: UINavigationBar {

    override func layoutSubviews() {
        super.layoutSubviews()

        for view in subviews {
            // Setting the layout margins to 0 lines the bar buttons items up at
            // the edges of the screen. You can set this to any number to change
            // the spacing.
            view.layoutMargins = .zero
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

要使用具有自定义按钮间距的新导航栏,您需要使用以下代码更新创建任何导航控制器的位置:

let navController = UINavigationController(navigationBarClass: InsetButtonsNavigationBar.self, 
                                                 toolbarClass: UIToolbar.self)
navController.viewControllers = [yourRootViewController]
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的回答.似乎现在应该改变设计以适应iOS 11的新UI更改,没有必要进行攻击并冒着预期的功能来收费或者用户界面打破.. (2认同)
  • 在Xcode 13 beta7中,iOS 13将引发异常:“尝试更改私有视图的布局边距的客户端错误” (2认同)