简体   繁体   English

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

[英]Swift : Logo on navigation bar along with back button

I want to have the logo of my app followed by the app name on the navigation bar. 我希望我的应用程序的徽标后跟导航栏上的应用程序名称。 Along with this, there should be a back button. 除此之外,应该有一个后退按钮。

Below is a screenshot : 以下是截图:

问题截图

I've tried the code below. 我试过下面的代码。

 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

This places the logo on top of the back button shown below. 这会将徽标放在下面显示的后退按钮的顶部。

截图2

How can this be achieved? 怎么能实现这一目标?

You can use custom view for navigationItem.titleView . 您可以使用navigationItem.titleView自定义视图。 Create UIView with your logo and a label for UIViewController title and set 使用您的徽标和UIViewController标题和集的标签创建UIView
navigationItem.titleView = YOUR_CUSTOM_VIEW;

Instead of using .leftBarButtonItem use: 而不是使用.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)

It will be added along with the system back button 它将与系统后退按钮一起添加 在此输入图像描述

You can find tons of example about it. 你可以找到很多关于它的例子。

In this example I've added also a space to centered well your logo if you needed: 在这个示例中,如果您需要,我还添加了一个空间,以便您的徽标居中:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM