如何在导航栏中添加自定义视图?
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];
【讨论】:
以上是关于如何在导航栏中添加自定义视图?的主要内容,如果未能解决你的问题,请参考以下文章