0

Mine screen contain UITabBar (tabs) and childViewController (content).

When I switch to another tab, I replace current child with next code:

private func replaceChild(_ old: UIViewController?, with new: UIViewController, in container: UIView) {
    old?.view.removeFromSuperview()
    old?.removeFromParentViewController()

    container.addSubviewWithConstraints(new.view)
    self.addChildViewController(new)

    self.replaceNavBar(with: new)
}

Also I try to steal barButtons from child and put them in VC:

private func replaceNavBar(with new: UIViewController) {
    self.title = new.title
    self.navigationItem.leftBarButtonItems  = new.navigationItem.leftBarButtonItems
    self.navigationItem.rightBarButtonItems = new.navigationItem.rightBarButtonItems
}

Console check rightBarButtonItem setting for first tab (right button +): Before:

oldVC: nil
newVC: <UIBarButtonItem: 0x7fb5f742bb50> target=0x7fb5f907c800 action=createNewMessage systemItem=Add

After:

oldVC: <UIBarButtonItem: 0x7fb5f742bb50> target=0x7fb5f907c800 action=createNewMessage systemItem=Add

Also if I set nil (for tabs, where no barButtons needed) - in debugger all show's OK and no error message happens.

But on UI, all buttons stays the same (if first tab was with buttons - buttons displayed and actions triggered. If it was no buttons -> no buttons). I store childs in array in main VC - so, no reinit happens

I'm pretty sure, that it's possible, because I've implement this flow some time ago and it works correct (put's child buttons to main VC, but stores target and selector), but I lost that code

Question: How I can steal barButtonItems from child VC and put them in parent VC navItem?

Upd I checked barButton setting with dumb code and it worked, but not on UI: breakpoints inside if and else blocks called by turns, but no button was added to navItem:

if let _ = self.navigationItem.rightBarButtonItem {
    self.navigationItem.rightBarButtonItem = nil
} else {
    let addButton = UIBarButtonItem.init(barButtonSystemItem: .add, target: nil, action: nil)
    addButton.tintColor = .white

    self.navigationItem.rightBarButtonItem = addButton
}

Also I tried version with self.navigationController?.navigationItem.rightBarButtonItem

Swift 4.1, Xcode 9.4.1

Viktor
  • 1,020
  • 1
  • 9
  • 22

1 Answers1

0

Solution found:

I forgot about very important thing - my VC is child for another one VC.

So I should perform not the self.navigationItem.rightBarButtonItem = ... but self.parent?.navigationItem.rightBarButtonItem = ...

Viktor
  • 1,020
  • 1
  • 9
  • 22