如何在导航栏中添加自定义视图?

Posted

技术标签:

【中文标题】如何在导航栏中添加自定义视图?【英文标题】:How to add custom view in navigation bar? 【发布时间】:2016-11-02 04:39:05 【问题描述】:

我想在我的导航栏上创建自定义视图。我在导航栏上有三个项目。在左侧我想在 UILabel 之后添加 UIImageView,在右侧添加 UIImage。现在我添加了右栏故事板右侧的按钮和添加的图像。我想将 Imageview 和 UILabel 添加到左侧。请告诉我如何添加它以便正确保持间隙。

【问题讨论】:

您可以通过编程方式将其添加到self.navigationController?.navigationBar 如果你只是想调整导航栏标题的位置,那么你可以设置一个UILabel作为标题视图,self.navigationItem.titleView = <UILabel> 【参考方案1】:
//FETECH BUTTON IMAGES FOR BOTH STATES NORMAL AND SELECTED
var normal= UIImage(contentsOfFile:NSBundle.mainBundle().pathForResource("FIRSTBUTTONIMG", ofType: ".png" , inDirectory: "FOLDER_PATH")!);

normal = normal?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

var selected = UIImage(contentsOfFile:NSBundle.mainBundle().pathForResource("FIRSTBUTTONIMGSELECTED ", ofType: ".png" , inDirectory: "FOLDER_PATH")!);

selected = selected?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

let Fbutton = UIButton(type: .Custom);

Fbutton.setImage(normal, forState: UIControlState.Normal)

Fbutton.setImage(selected, forState: UIControlState.Selected)

Fbutton.addTarget(self, action:#selector(YOURBTNACTION(_:)), forControlEvents: .TouchUpInside)

Fbutton.frame=CGRectMake(0, -6, 53, 53)

//ADD YOUR CUSTOM VIEW AND ADD ABOVE BUTTON INSIDE CUSTOM VIEW
let CustomView = UIView()

CustomView.frame=CGRectMake(0, 0, Fbutton.frame.height, Fbutton.frame.width);

CustomView.addSubview(Button)

//ADD MORE ITEMS  TO CUSTOM VIEW IF NEEDED

//ADD THAT CUSTOM VIEW TO UIBarButtonItem

let CustomViewButton:UIBarButtonItem = UIBarButtonItem(customView: backCustomView)

//ASSIGN THAT UIBarButtonItem TO leftBarButtonItems AS ARRAY ITEM
self.navigationItem.leftBarButtonItems=[CustomViewButton,MORE ITEM IF NEEDED];

【讨论】:

以上是关于如何在导航栏中添加自定义视图?的主要内容,如果未能解决你的问题,请参考以下文章

单击导航栏中的“返回”按钮时如何设置自定义视图控制器?

如何创建自定义标签栏...在标签栏中添加自定义图像(无需 xib 更改)

如何在 swift 中使用自定义导航栏制作三个分页视图

如何在导航栏 Swift 右侧添加自定义视图?

Wordpress 导航栏中的自定义简码

导航栏标题视图与左栏按钮项重叠