导航栏返回按钮的定制

来源:互联网 发布:伊戈达拉身体数据 编辑:程序博客网 时间:2024/05/21 12:40

导航栏自带一个返回按钮,我们需要定制它的样式,这可以有许多办法。比如 Hack 导航栏的视图层次。如果你不想 Hack 导航栏,那么你可以使用NavigationBarDelegate。问题在于,如果是导航控制器自带的NavigationBar,你将不能访问NavigationBar(程序会Crash)。这是苹果文档中的说明:

Note that if you use aUINavigationController object to manage hierarchical navigation, you should notdirectly access the navigation bar object.

这里,我们提供另一种“定制”方法。也许不能称之为定制,因为我们实际上是将默认的返回按钮隐藏了,并提供一个自定义的返回按钮作为导航栏的leftButton。使用这种方法,我们不仅可以定制按钮的样式(标题和背景图片),而且可以触发自定义的方法。默认的返回按钮动作是popViewController,我们可以修改为其他动作。

这个过程大概分为4个步骤:

1、隐藏默认返回按钮,这是通过设置navigationItem的hidesBackButton为YES做到的:

// 隐藏默认的”返回”按钮

[self.navigationItemsetHidesBackButton:YES];

2、自定义一个BarButtonItem。首先,我们定制一个UIButton。 这个UIButton用buttonWithType:UIButtonTypeCustom方法初始化。然后用setBarckgroundImage方法定制按钮的背景图片,用addTarget方法指定按钮的事件处理方法。这样我们就获得了一个完全定制的Button。BarButtonItem有一个initWithCustomView:的初始化方法。我们可以把一个定制的视图(比如我们定制的Button)作为这个方法的参数,构建出一个BarButtonItem。

// 自定义导航栏的”返回”按钮

UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeCustom];

btn.frame = CGRectMake(15, 5, 38, 38);

[btn setBackgroundImage:[UIImageimageNamed:@”按钮-返回1.png”] forState:UIControlStateNormal];

[btn addTarget: selfaction: @selector(goBackAction) forControlEvents: UIControlEventTouchUpInside];

UIBarButtonItem*back=[[UIBarButtonItemalloc]initWithCustomView:btn];

3、把BarButtonItem 设置为 navigationItem的leftBarButton。

// 设置导航栏的leftButton

self.navigationItem.leftBarButtonItem=back;

4、编写Button的事件代码。

-(void)goBackAction{

// 在这里增加返回按钮的自定义动作

[self.navigationControllerpopViewControllerAnimated:YES];

}

0 0
原创粉丝点击