Swift : 导航栏上的徽标和后退按钮

Swift : Logo on navigation bar along with back button

我想在导航栏上显示我的应用程序徽标,后跟应用程序名称。除此之外,还应该有一个后退按钮。

下面是截图:

我试过下面的代码。

 self.navigationItem.setHidesBackButton(false, animated:true);

 let imgLogo : UIImage = UIImage(named:"Logo")!
 let imgViewLogo : UIImageView = UIImageView(image: imgLogo)
 imgViewLogo.frame = CGRectMake(0, 0, 40, 40)

 let leftItem:UIBarButtonItem = UIBarButtonItem(customView: imgViewLogo)
 self.navigationItem.leftBarButtonItem = leftItem
 // App Name set on storyboard at design-time

这会将徽标放在后退按钮的顶部,如下所示。

如何实现?

您可以为 navigationItem.titleView 使用自定义视图。使用您的徽标和 UIViewController 标题标签创建 UIView 并设置
navigationItem.titleView = YOUR_CUSTOM_VIEW;

而不是使用 .leftBarButtonItem 使用:

let imgLogo : UIImage = UIImage(named:"Logo")!
    let imgViewLogo : UIImageView = UIImageView(image: imgLogo)
    imgViewLogo.frame = CGRectMake(0, 0, 40, 40)

    let leftItem:UIBarButtonItem = UIBarButtonItem(customView: imgViewLogo)
    self.navigationItem.leftBarButtonItems?.append(leftItem)

它将与系统后退按钮一起添加

你可以找到大量关于它的例子。

在此示例中,如果您需要,我还添加了一个 space 以使您的徽标居中:

let leftButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "Logo")!, style: UIBarButtonItemStyle.Plain, target: self, action:#selector(MyViewController.leftButtonPress(_:)))
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
negativeSpacer.width = -5.0 // Left inset to better center your logo
navigationItem.leftBarButtonItems = [negativeSpacer,leftButton]

func leftButtonPress(sender: AnyObject?) {
    // do whatever you want when you press back button
}