由于iOS 11和Xcode 9 BarbuttonItems和标题不再可见。我是否试图添加这样的自定义视图都没关系:
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)
或仅像这样的标准uibarbuttonems:
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一切正常。
此问题是在用Xcode 9编译时出现的,因为现在UIBarButtonItem
也使用autoLayput。below是使其正常工作的代码。
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]];
我在更新到xCode9
IDE时也有相同的问题。我能够使用UINavigationBar.appearance
:
let buttonItem = UIButton.appearance(whenContainedInInstancesOf: [UINavigationBar.self])
buttonItem.setTitleColor(.black, for: .normal)
buttonItem.setTitleColor(.gray, for: .disabled)
我也有同样的问题,并且没有上述问题。我要做的就是在titleView
上设置width
,一切都很好!
编辑:
每个UIViewController
都有navigationItem
属性,每个navigationItem
都有一个可选的titleView
。
参考:https://developer.apple.com/documentation/uikit/uinavigationitem/1624935-titleview
就我而言,我正在使用自定义titleView
,我认为这是问题的原因,因为Apple更改了API以支持新的导航栏布局。