UINavigationBar BarButtonItem с простым стилем - PullRequest
20 голосов
/ 27 февраля 2010

я получил следующий код:

- (id)init {
  if (self = [super init]) {
      self.title = @"please wait";
      UIBarButtonItem *favorite = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"star.png"] style:UIBarButtonItemStylePlain target:self action:@selector(buttonFavoriteClicked:)];
      self.navigationItem.rightBarButtonItem = favorite;
  }

  return self;
}

но моя кнопка по-прежнему выглядит как кнопка с UIBarButtonItemStyleBordered alt text

есть ли способ установить кнопку с простым стилем в этой позиции?

Ответы [ 8 ]

23 голосов
/ 24 мая 2010

Создайте UIButton в конструкторе интерфейсов, чтобы он выглядел именно так, как вы хотите. Создайте выход для в вашем .h:

IBOutlet UIButton * _myButton;

Затем установите его в качестве элемента правой кнопки панели, используя пользовательский вид, который удалит границу:

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_myButton];

Это работает, потому что UIButton является подклассом UIView.

23 голосов
/ 26 марта 2010

Попробуйте вместо этого:

- (id)init {
  if (self = [super init]) {
      self.title = @"please wait";

      UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
      [button setImage:[UIImage imageNamed:@"star.png"] forState:UIControlStateNormal];
      [button addTarget:self action:@selector(buttonFavoriteClicked) forControlEvents:UIControlEventTouchUpInside];
      UIBarButtonItem *favorite = [[UIBarButtonItem alloc] initWithCustomView:button];
      [button release];

      self.navigationItem.rightBarButtonItem = favorite;
  }

  return self;
}

Надеюсь, это поможет.

8 голосов
/ 21 ноября 2011

Или сделать это в коде без IB:

// add setting button to nav bar
UIImage* settingsGearImg = [UIImage imageNamed:@"settings_gear.png"];
CGRect frameimg = CGRectMake(0, 0, settingsGearImg.size.width, settingsGearImg.size.height);
UIButton *settingsButton = [[UIButton alloc] initWithFrame:frameimg];
[settingsButton setBackgroundImage:settingsGearImg forState:UIControlStateNormal];
[settingsButton addTarget:self action:@selector(settingsButtonAction) forControlEvents:UIControlEventTouchUpInside];
[settingsButton setShowsTouchWhenHighlighted:YES];
UIBarButtonItem *settingButtonItem =[[UIBarButtonItem alloc] initWithCustomView:settingsButton];
self.navigationItem.leftBarButtonItem = settingButtonItem;

Результат:

enter image description here

При использовании этого изображения значка (оно белое на белом фоне, поэтому здесь его не видно - ссылка: http://i.stack.imgur.com/lk5SB.png): enter image description here

4 голосов
/ 10 февраля 2013

Это странно, но работает. Скажите «Нет» изображениям / розеткам! Вы даже не должны устанавливать свойство UIBarButtonItemStylePlain. Хитрость заключается в том, чтобы поместить кнопку в UIToolBar с некоторыми специальными атрибутами:

UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"Cool plain bar"];
UIToolbar *tools = [[UIToolbar alloc]
                    initWithFrame:CGRectMake(0.0f, 0.0f, 44.0f, 44.01f)];
tools.clipsToBounds = NO;
tools.barStyle = -1; // clear background
NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:1];
UIBarButtonItem *bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshTableView)];
[buttons addObject:bi];
[tools setItems:buttons animated:NO];
UIBarButtonItem *rightButtons = [[UIBarButtonItem alloc] initWithCustomView:tools];

item.rightBarButtonItem = rightButtons;
item.hidesBackButton = YES;
[myCoolNavigationBar pushNavigationItem:item animated:NO];
1 голос
/ 27 февраля 2010

Хотя Фрэнк прав, этот код должен быть в viewDidLoad, проблема в том, как выглядят кнопки BarButton.Если вы хотите, чтобы он выглядел по-другому, вам нужно использовать другой тип UIView.Вы можете просто добавить UIButton в UIToolbar.

-(void)viewDidLoad {
  [super viewDidLoad];
  self.title = @"please wait";
  self.navigationItem.rightBarButtonItem = [[[UIButton alloc] init] autorelease];
}

Редактировать:

Извините, вы хотели простой UIBarButtonItem.Я не верю, что вы можете сделать это с помощью UINavigationBar.Вы можете попробовать добавить UserInteractionEnabled UILabel в качестве rightBarButtonItem, я не уверен, будет ли он работать или нет.

Кажется, что в настоящее время это невозможно.
sbwoodside имеет решение .

0 голосов
/ 25 ноября 2013

Почему бы не попробовать UI7Kit? Хорошо работает для меня, прост в использовании.

0 голосов
/ 09 февраля 2013

Попробуйте это,

UIBarButtonItem *barBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"more.png"] style:UIBarButtonItemStylePlain target:self action:@selector(didPressButton)];
0 голосов
/ 22 августа 2011
    UIImage *img = [UIImage imageNamed:@"white_star.png"];

      CGSize itemSize = CGSizeMake(20, 20);
      UIGraphicsBeginImageContext(itemSize);
      CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
      [img drawInRect:imageRect];
      img = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();


  UIBarButtonItem *barButton = [[UIBarButtonItem alloc ] initWithImage:img style:UIBarButtonSystemItemAdd target:self action:@selector(favoriteButtonClicked)];
  barButton.style = UIBarButtonItemStyleBordered;
...