自定义TabViewController - navigationItem.rightBarButtonItem不会显示在导航栏中

时间:2018-01-18 05:46:37

标签: ios swift uinavigationbar uibarbuttonitem uinavigationitem

我使用自定义TabViewController。我想更改右侧的条形按钮项目仅限于CompanyViewController 。但是,更改self.navigationItem.rightBarButtonItem无法正常工作 - 该按钮不会显示在导航栏上。我该如何解决这个问题?

CompanyViewController.swift

let filterButton = UIBarButtonItem(title: "Filters Off", style: .plain, target: self, action: #selector(filterButtonTapped))

self.navigationController?.navigationBar.topItem?.rightBarButtonItem = filterButton // Works
self.navigationItem.rightBarButtonItem = filterButton //Doesn't work

Resource

1 个答案:

答案 0 :(得分:0)

请使用此代码:

//Create custom UIButton with image.

let filterButton = UIButton(type: .custom)
filterButton.setImage(UIImage(named: "imagename"), for: .normal)
filterButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
filterButton.addTarget(self, action: #selector(Class.Methodname), for: .touchUpInside)

//Assign that UIButton to UIBarButtonItem
let item1 = UIBarButtonItem(customView: filterButton)

//set UIBarButtonItem to navigationItem
self.navigationItem.setRightBarButtonItems([item1], animated: true)