自定义UI导航栏和button
你好我是新来的ios开发,并想知道如何自定义导航栏button
这是我用来改变导航栏的颜色
[[UINavigationBar appearance] setBarTintColor:[UIColor]]
我想改变button的颜色
这是一个例子
首先你需要设置导航栏,假设你的第一个屏幕是SpalshViewController,你需要设置启动屏幕作为导航栏的根视图控制器,然后将导航栏设置为根视图控制器,如:
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; SplashScreenVC *obj =[CustomUtility getViewController:@"SplashScreenVC"]; self.navigationController =[[UINavigationController alloc] initWithRootViewController:obj]; self.window.rootViewController =self.navigationController;
在didFinishLaunchingWithOptions
现在来自定义导航栏的设置和外观,你需要设置:
self.navigationController.navigationBar.translucent = NO; [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"top_bg2.png"] forBarMetrics:UIBarMetricsDefault]; [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor],NSFontAttributeName:[UIFont fontWithName:@"Lato-Regular" size:18]}];
现在设置导航栏的自定义栏button,你需要创buildbarbutton项目,如:
UIBarButtonItem *leftbtn; UIBarButtonItem *rightbtn; [self.navigationController.navigationItem setLeftBarButtonItem:leftbtn]; [self.navigationController.navigationItem setRightBarButtonItem:rightbtn];
自定义barbuttonItems
根据您的需要
如果你想设置多个button到导航栏,你可以添加像:
UIBarButtonItem *leftbtn1; UIBarButtonItem *leftbtn2; UIBarButtonItem *rightbtn1; UIBarButtonItem *rightbtn2; [self.navigationController.navigationItem setLeftBarButtonItems:@[leftbtn1,leftbtn2]]; [self.navigationController.navigationItem setRightBarButtonItems:@[rightbtn1,rightbtn2]];
希望这会对你有所帮助
您可以使用下面的导航栏进行自定义。 在故事板中,您可以select更改颜色。
否则,你可以把UIView进行自定义。 如下所示,
用你想要的颜色创build一个1×1像素的图像。 然后将下面的代码添加到您的AppDelegate类。
UIImage *btnBgColor = [[UIImage imageNamed:@"backColor"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)]; [[UIBarButtonItem appearance] setBackgroundImage: btnBgColor forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
要么
把下面的代码写在你的viewController类的基础上,然后把这个类作为所有其他视图控制器的超类。
UIButton* yourButton = [UIButton buttonWithType:UIButtonTypeCustom]; yourButton.layer.backgroundColor = [UIColor redColor].CGColor; UIBarButtonItem* buttonItem = [[UIBarButtonItem alloc] initWithCustomView: yourButton]; self.navigationBar.leftBArButtonItems = @[buttonItem];
您可以在导航栏中添加自定义button,如:
UIButton *btnObj = [UIButton buttonWithType:UIButtonTypeCustom]; [btnObj setFrame:CGRectMake(0, 0, 60, 44)]; [btnObj setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter]; [btnObj setImage:[UIImage imageNamed:@"<button background image>"] forState:UIControlStateNormal]; [btnObj addTarget:self action:@selector(btnObjClick:) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *itemBtnObj = [[UIBarButtonItem alloc] initWithCustomView:btnObj]; self.navigationItem.rightBarButtonItems = [[NSArray alloc]initWithObjects:itemBtnObj, nil];
你可以从故事板本身做到。 拖动UINavigation Bar
使用图像或背景颜色自定义您的导航给他们的阴影。
添加导航项目
您也可以根据需要使用图像或颜色以及图像和位置对其进行自定义。
要添加约束到相同的引用我的答案。 将约束添加到UIBarButtonItem
希望它有助于..快乐编码.. 🙂