如何在条形图标题上为导航控制器的工具栏添加标题和图像

时间:2018-04-10 16:26:39

标签: ios swift uinavigationcontroller uibarbuttonitem

如何在导航控制器上的UIBarButtonItem上添加图像和文本,就像在照片,ebay等现代应用上一样(参见Toolbar

我知道如果您手动将工具栏添加到视图中,这可以在Interface Builder中实现,但如果使用导航控制器则无法做到这一点。

2 个答案:

答案 0 :(得分:0)

如果UIViewController中有UINavigationController,您可以使用

设置视图控制器的左右按钮
// System item
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(action))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(action))
// Tittle
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Left Button", style: .plain, target: self, action: #selector(action))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Right Button", style: .plain, target: self, action: #selector(action))
// Image
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(action))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(action))
// Custom view
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: view)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)

答案 1 :(得分:0)

到目前为止,这是我的目标。但是,这仅显示图像右侧的文本:

   //Create a UIButton with an image on the left, and text to the right
    var buttonImage = #imageLiteral(resourceName: "Lab")
    var button : UIButton = UIButton(type: UIButtonType.custom)
    button.setImage(buttonImage, for: UIControlState.normal);
    button.setTitle("Caption", for: UIControlState.normal);