免费开源的iOS开发学习平台

UINavigationController介绍:10-UINavigationItem显示原始图片样式

通过UINavigationBar的tintColor属性,我们可以修改导航栏整体的颜色渲染方式,但在实际的开发过程中,导航栏中的控件样式通常是由设计师设计好的,有其固定的颜色,所以,通常情况下,我们需要显示控件的原始样式。

方法简介

在UIBarButtonItem的初始化方法中,提供了initWithCustomView:方法,该方法需要传入一个UIView的对象,因此,我们可以考虑传入一个UIButton对象,把原始图片设置为该UIButton的图片。

- (instancetype)initWithCustomView:(UIView *)customView;

示例代码

下方的示例代码中,我们创建了一个UIButton类的对象,并且对该按钮的样式进行了定制,为了使UIBarButtonItem类的对象显示UIButton的样式,需要使用initWithCustomView:实例化方法。

    //实例化一个UIButton对象,并设置图片
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 44, 44);
    [rightBtn setImage:[UIImage imageNamed:@"write_comment"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(clickRightBarButton) forControlEvents:UIControlEventTouchUpInside];

    //实例化UIBarButtonItem对象
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    navRootVC.navigationItem.rightBarButtonItem = rightBarButtonItem;

显示效果:

示例代码

https://github.com/99ios/9.2.10