导航栏按钮文字消失

时间:2016-09-14 16:24:30

标签: swift xcode

我在屏幕顶部有2个导航栏按钮,一个带有图像,另一个带有文字,如下所示:

enter image description here

当我使用新的导航控制器/根控制器呈现一个新的视图控制器然后将其关闭时,返回到同一个视图控制器,文本就会消失:

enter image description here

这里是视图控制器的代码

override func viewDidLoad() {
    setupNavBarButtons()
}

func setupNavBarButtons() {
    let searchImage = UIImage(named: "search_icon")?.imageWithRenderingMode(.AlwaysOriginal)
    let searchBarButtonItem = UIBarButtonItem(image: searchImage, style: .Plain, target: self, action: #selector(handleSearch))
    navigationItem.rightBarButtonItem = searchBarButtonItem

    let filterBarButtonItem = UIBarButtonItem(title: "Filter", style: .Plain , target: self, action: #selector(displayFilter))
    navigationItem.leftBarButtonItem = filterBarButtonItem
}


func presentAccountController() {
    let accountController = AccountController()
    accountController.listController = self
    let vc = UINavigationController(rootViewController: accountController
    presentViewController(vc, animated: true, completion: nil)
}

控制器我不想返回原始视图控制器:

class AccountController: UIViewController, UITableViewDelegate, UITableViewDataSource, MFMailComposeViewControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    setupViews()
    view.backgroundColor = UIColor.rgb(245, green: 245, blue: 245)

    let closeButtonItem = UIBarButtonItem(title: "Close", style: .Plain, target: self, action: #selector(dismissController))
    navigationItem.leftBarButtonItem = closeButtonItem
}

func dismissController() {
    self.dismissViewControllerAnimated(true, completion: nil)
}

我试过在viewWillLoad,viewDidLoad,viewDidAppear中调用它。仍然没有变化,但仍然会发生错误。

1 个答案:

答案 0 :(得分:0)

您可以这样做并在创建按钮时创建一个带有宽 width 的框架

lazy var filterButton: UIButton = {
    let button = UIButton(type: .system)
    button.frame = CGRect(x: 0, y: 0, width: 60, height: 30) // Set the width here to make it wider
    button.setTitle("Filter", for: .normal)
    button.titleLabel?.font = UIFont.systemFont(ofSize: 18)
    button.setTitleColor(UIColor.white, for: .normal)
    button.addTarget(self, action: #selector(filterButtonTapped), for: .touchUpInside)
    return button
}()

var leftBarButtonItem: UIBarButtonItem?

override func viewDidLoad() {
    super.viewDidLoad()

    leftBarButtonItem = UIBarButtonItem(customView: filterButton)
    navigationItem.leftBarButtonItem = leftBarButtonItem
}

@objc func filterButtonTapped() {

    print("Filter button tapped")
}