如何将导航栏按钮放在自定义位置

时间:2013-06-04 18:18:59

标签: ios

我当前的导航栏如下所示:

enter image description here

如您所见,我需要将其移至右侧。不确定我是否正确设置了这个,有什么建议吗?

以下是代码:

-(void)customizeNavigationBar{

    //*** Nav bar Background ***
    //Image being used
    UIImage *backgroundImage = [UIImage imageNamed:@"navBarBackground"];

    //Set navigation bar image
    [self.navigationController.navigationBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];

    //*** Search button**
    //Get Image
    UIImage* searchImage = [UIImage imageNamed:@"navSearchButton"];

    //Set frame
    CGRect frame = CGRectMake(0, 0, searchImage.size.width, searchImage.size.height);

    //Create button
    UIButton *searchButton = [[UIButton alloc] initWithFrame:frame];

    //Set background images (selected and not)
    [searchButton setBackgroundImage:searchImage forState:UIControlStateNormal];
    [searchButton setBackgroundImage:[UIImage imageNamed:@"navSearchButtonSelected"] forState:UIControlStateSelected];

    //Add action
    [searchButton addTarget:self action:@selector(search)
          forControlEvents:UIControlEventTouchUpInside];

    //Set highlight on
    [searchButton setShowsTouchWhenHighlighted:YES];

    //Create nav buttons
    UIBarButtonItem *navSearchBtn =[[UIBarButtonItem alloc] initWithCustomView:searchButton];

    //Add to nav bar
    [self.navigationItem setLeftBarButtonItem:navSearchBtn];
}

1 个答案:

答案 0 :(得分:1)

  • 使用setImage:forState:用于将背景图像设置为UIButton(而不是setBackgroundImage:)
  • 将UIButton的帧设置得稍大(size.width)