Вандад Нахавандипур

iOS. Приемы программирования


Скачать книгу

добавим кнопку в правую часть нашей навигационной панели. На этой кнопке будет написано Add (Добавить):

      – (void) performAdd:(id)paramSender{

      NSLog(@"Action method got called.");

      }

      – (void)viewDidLoad{

      [super viewDidLoad];

      self.title = @"First Controller";

      self.navigationItem.rightBarButtonItem =

      [[UIBarButtonItem alloc] initWithTitle:@"Add"

      style: UIBarButtonItemStylePlain

      target: self

      action:@selector(performAdd:)];

      }

      Если сейчас запустить приложение, появится картинка, примерно как на рис. 1.37.

      Рис. 1.37. Навигационная кнопка, добавленная на навигационную панель

      Пока все просто. Но если вы регулярно пользуетесь iOS, то, вероятно, заметили, что в системных приложениях iOS применяется готовая конфигурация и кнопка Add (Добавить) там выглядит иначе. На рис. 1.38 показан пример из раздела Alarm (Будильник) приложения Clock (Часы) для iPhone. Обратите внимание на кнопку + в верхней правой части навигационной панели.

      Рис. 1.38. Правильный способ создания кнопки Add (Добавить)

      Оказывается, в SDK iOS можно создавать системные кнопки. Это делается с помощью метода-инициализатора nitWithBarButtonSystemItem: target: action:, относящегося к классу UIBarButtonItem:

      – (void) performAdd:(id)paramSender{

      NSLog(@"Action method got called.");

      }

      – (void)viewDidLoad{

      [super viewDidLoad];

      self.title = @"First Controller";

      self.navigationItem.rightBarButtonItem =

      [[UIBarButtonItem alloc]

      initWithBarButtonSystemItem: UIBarButtonSystemItemAdd

      target: self

      action:@selector(performAdd:)];

      }

      В результате получится именно то, чего мы добивались (рис. 1.39).

      Первый параметр метода-инициализатора initWithBarButtonSystemItem: target: action:, относящегося к навигационной кнопке, может принимать в качестве параметров любые значения из перечня UIBarButtonSystemItem:

      Рис. 1.39. Системная кнопка Add (Добавить)

      typedef NS_ENUM(NSInteger, UIBarButtonSystemItem) {

      UIBarButtonSystemItemDone,

      UIBarButtonSystemItemCancel,

      UIBarButtonSystemItemEdit,

      UIBarButtonSystemItemSave,

      UIBarButtonSystemItemAdd,

      UIBarButtonSystemItemFlexibleSpace,

      UIBarButtonSystemItemFixedSpace,

      UIBarButtonSystemItemCompose,

      UIBarButtonSystemItemReply,

      UIBarButtonSystemItemAction,

      UIBarButtonSystemItemOrganize,

      UIBarButtonSystemItemBookmarks,

      UIBarButtonSystemItemSearch,

      UIBarButtonSystemItemRefresh,

      UIBarButtonSystemItemStop,

      UIBarButtonSystemItemCamera,

      UIBarButtonSystemItemTrash,

      UIBarButtonSystemItemPlay,

      UIBarButtonSystemItemPause,

      UIBarButtonSystemItemRewind,

      UIBarButtonSystemItemFastForward,

      #if __IPHONE_3_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED

      UIBarButtonSystemItemUndo,

      UIBarButtonSystemItemRedo,

      #endif

      #if __IPHONE_4_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED

      UIBarButtonSystemItemPageCurl,

      #endif

      };

      Один из самых интересных инициализаторов из класса UIBarButtonItem – метод initWithCustomView:. В качестве параметра этот метод может принимать любой вид, то есть мы даже можем добавить на навигационную панель в качестве навигационной кнопки UISwitch (см. раздел 1.2). Это будет выглядеть не очень красиво, но мы просто попробуем:

      – (void) switchIsChanged:(UISwitch *)paramSender{

      if ([paramSender isOn]){

      NSLog(@"Switch is on.");

      } else {

      NSLog(@"Switch is off.");

      }

      }

      – (void)viewDidLoad{

      [super viewDidLoad];

      self.view.backgroundColor = [UIColor whiteColor];

      self.title = @"First Controller";

      UISwitch *simpleSwitch = [[UISwitch alloc] init];

      simpleSwitch.on = YES;

      [simpleSwitch addTarget: