导航栏NavigationBar的按钮设置

有时候在自定义navigationBar的左右按钮的时候,button的图片会显得很大,个人感觉原因有以下几种情况:

1、使用的是UIButton直接加在navigationBar上面
2、自定义了一个UIView,顶替系统的NavigationBar,button的frame值设置有问题。

如果是第一种情况解决方法如下:

    //左边城市选择
   UIButton *LButton =[UIButton buttonWithType:UIButtonTypeCustom];
   LButton.frame = CGRectMake(0, 0, 40, 30);
   LButton.imageEdgeInsets= UIEdgeInsetsMake(0, 20, 0, 0);
   [LButton setTitle:@"长沙" forState:UIControlStateNormal];
   LButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
   UIBarButtonItem *leftButton=[[UIBarButtonItem alloc]initWithCustomView:LButton];

   self.navigationItem.leftBarButtonItem = leftButton;
 
   // 右边search按钮
   UIButton *RButton =[UIButton buttonWithType:UIButtonTypeCustom];
   RButton.frame = CGRectMake(0, 0, 40, 30);
   [RButton setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
   
   UIBarButtonItem *rightButton=[[UIBarButtonItem alloc]initWithCustomView:RButton];  
   self.navigationItem.rightBarButtonItem = rightButton;

针对第二种情况:
如果只是想获取系统的按钮的话, 因为 navigation bar 上的按钮是 UIBarButtonItem 类的, 所以位置和大小是按内容自动生成的, 获取时也需要通过UIEvent 获取. 例如:

- (void)myButtonPressed:(UIBarButtonItem *)button event:(UIEvent *)event 
{
   NSLog(@"%@", [event.allTouches.anyObject view]);
}

输出: UINavigationButton: 0x71cf400; frame = (281 7; 34 30); opaque = NO; layer = <CALayer: 0x718e950>
 (这是一个位于navigation bar右侧使用了refresh系统图标的按钮)

posted @ 2018-09-07 16:50  光是光光的光呐  阅读(2816)  评论(0编辑  收藏  举报