BarButtonItems和标题没有出现在iOS 11中

问题描述:

由于iOS 11和Xcode 9 barbuttonitems和标题不再可见。不要紧,我是否尝试添加自定义视图这样的:BarButtonItems和标题没有出现在iOS 11中

let backButton = UIButton.init(frame: CGRect(x: 0, y: 0, width: 180, height: 32)) 
     backButton.setImage(UIImage(named: "back_icon")?.withRenderingMode(.alwaysTemplate), for: .normal) 
     backButton.tintColor = UIColor.white 
     backButton.addTarget(self, action: #selector(backAction), for: .touchUpInside) 
     backButton.backgroundColor = UIColor.clear 
     backButton.titleLabel?.font = UIFont(name: SWMainHelper.sharedInstance.mediumFont, size: 18) 
     backButton.setTitleColor(UIColor.white, for: .normal) 
     backButton.setTitle("Go back", for: .normal) 

     backButton.sizeToFit() 

     backButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0) 

     backButton.frame.size.width += 16 

     let negativeButtonSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) 
     negativeButtonSpace.width = -16 

     self.navigationItem.setLeftBarButtonItems([negativeButtonSpace, UIBarButtonItem(customView: backButton)], animated: true) 

或只是标准的UIBarButtonItems这样的:

let add = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped)) 
     add.tintColor = UIColor.white 
     let play = UIBarButtonItem(title: "Play", style: .plain, target: self, action: #selector(playTapped)) 
     play.tintColor = UIColor.white 
     navigationItem.rightBarButtonItems = [add, play] 

和Xcode 8一切正常。

当更新到xCode9 IDE时,我遇到了同样的问题。我能够通过使用UINavigationBar.appearance来解决此问题:

let buttonItem = UIButton.appearance(whenContainedInInstancesOf: [UINavigationBar.self]) 
    buttonItem.setTitleColor(.black, for: .normal) 
    buttonItem.setTitleColor(.gray, for: .disabled) 
+0

遗憾的是没有解决我的问题。不管怎么说,还是要谢谢你! –

奇怪的是,在那个地方都没有添加的按钮(你可以看到这个所附照片)。

enter image description here

我有上述的同样的问题,并没有固定。 我所做的只是在titleView上设置了width,一切正常!

编辑:

UIViewControllernavigationItem属性,每个navigationItem有一个可选的titleView

参考:https://developer.apple.com/documentation/uikit/uinavigationitem/1624935-titleview

对我来说,我使用的是自定义的titleView,我认为这是问题的原因,因为苹果改变以支持新的导航栏布局的API。

编译Xcode 9时出现此问题,因为现在UIBarButtonItem也在使用autolayput。下面是它使其工作的代码。

UIButton *leftCustomButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35, 100)]; 

     [leftCustomButton.widthAnchor constraintEqualToConstant:100].active = YES; 
     [leftCustomButton.heightAnchor constraintEqualToConstant:35].active = YES; 
     [leftCustomButton setTitle:@"TEST" forState:UIControlStateNormal]; 
     [leftCustomButton.titleLabel setFont:[UIFont boldSystemFontOfSize:16.0]]; 
     [leftCustomButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
     UIBarButtonItem * leftButtonItem =[[UIBarButtonItem alloc] initWithCustomView:leftCustomButton];   
     [self.navigationItem setRightBarButtonItems:@[leftButtonItem]];