Подтвердить что ты не робот

IOS 7 BarButtonItem с изображением и заголовком

Я пытаюсь понять, как я могу добиться чего-то вроде этого:

enter image description here

Это панель инструментов, и я бы хотел оставить текст названия кнопки без создания всего изображения с иконкой И текстом. Как добавить значок слева от UIBarButtonItem, сохраняя при этом текст с помощью:

UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Button" style:UIBarButtonItemStyleBordered target:nil action:nil];

ИЗМЕНИТЬ

Это то, что я достиг с помощью следующего кода:

    UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [customButton setImage:[UIImage imageNamed:@"Test"] forState:UIControlStateNormal];
    [customButton setTitle:@"Button" forState:UIControlStateNormal];
    customButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [customButton sizeToFit];
    UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];

enter image description here

Два вопроса: первый - размер UIButton, а второй - это то, что, как вы можете видеть из gif, кнопка не анимируется должным образом, когда я нажимаю внутри кнопки, и когда я отпускаю кран, Любые идеи?

4b9b3361

Ответ 1

Вы можете встроить UIButton в качестве пользовательского представления внутри вашего UIBarButtonItem. Вы можете создать свой UIButton, как хотите, в том числе с изображением и текстом, используя -setImage:forState: и -setTitle:forState:.

UIButton* customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
[customButton setTitle:@"Button" forState:UIControlStateNormal];
[customButton sizeToFit];
UIBarButtonItem* customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];
self.navigationItem.leftBarButtonItem = customBarButtonItem; // or self.navigationItem.rightBarButtonItem

Обратите внимание, что при этом вам необходимо прикрепить свои методы IBAction к customButton, а не к customBarButtonItem.

Для получения дополнительной информации см. документацию для initWithCustomView:.

Вы также можете сделать все это в построителе интерфейса, просто перетащив UIButton в левую панель/правую кнопку на панели навигации.

Ответ 2

Я не был удовлетворен всеми решениями, найденными при переполнении стека, потому что мне нравится, как UIBarButtonItenm конвертирует изображения, чтобы они отображались правильно, и их можно изменить цветом оттенка. Поэтому я обнаружил это решение, которое можно использовать с небольшим количеством кода... Конечный эффект похож на панель инструментов в facebook и других текущих приложениях...

enter image description here

При изменении цвета оттенка, содержащегося в UIBArButtonItem, цвета изображения и изменение названия соответственно, действительно здорово, мне вообще не нужно создавать специальные изображения.

Этот код вызывается с каждой кнопки, такой как кнопка Конкурса, а также кнопка устанавливается как ссылка на выход...

- (void)selectButton:(UIButton *)sender { 
    _competitionButton.superview.tintColor = [UIColor lightGrayColor];
    _usersButton.superview.tintColor = [UIColor lightGrayColor]; 
    _managementButton.superview.tintColor = [UIColor lightGrayColor];    
    sender.superview.tintColor = [UIColor whiteColor]; 
}

- (IBAction)onCompetitionButtonClick:(UIButton *)sender {
    [self selectButton:sender];
    [_scrollView scrollToPage:0 of:3];
}

В Button, подобном названному Конкуренту, есть только название, а в элементе bar button есть изображение... Вот как я его настроил, и он работает, возможно, есть и другие возможности.

Ответ 3

Итак, мне удалось сделать свое решение программно... Некоторые пользователи, которые жалуются на него, не работают... Итак, как создать UTToolbar с изображением и элементом, чтобы вы могли менять цвет кнопки по оттенку, и это волшебным образом изменяет изображение как а как ярлык названия? Мое решение для редактора пользовательского интерфейса работает точно... В этом коде можно прояснить многое, и вы можете сделать это программно...

- (void)loadToolbar {
    NSMutableArray *items = NSMutableArray.new;
    [items add:[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]];
    for (uint pageIndex = 0; pageIndex < _controllers.count; ++pageIndex) {
        UIView *itemView = [UIView.alloc initWithFrame:CGRectMake(0, 0, 100, 44)];
        itemView.backgroundColor = [UIColor clearColor];
        itemView.tintColor = [UIColor orangeColor];
        [itemView addSubview:[self createToolbarForItemView:pageIndex]];
        [itemView addSubview:[self createButtonForItemView:pageIndex]];
        UIBarButtonItem *item = [UIBarButtonItem.alloc initWithCustomView:itemView];
        item.style = UIBarButtonItemStylePlain;
        [items add:item];
        [items add:[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]];
    }
    [_toolbar setItems:items];
}

- (UIButton *)createButtonForItemView:(uint)pageIndex {
    UIButton *itemButton = [UIButton buttonWithType:UIButtonTypeSystem];
    itemButton.frame = CGRectMake(0, 0, 100, 44);
    itemButton.titleLabel.font = [UIFont systemFontOfSize:11];
    itemButton.contentEdgeInsets = UIEdgeInsetsMake(30, 0, 0, 0);
    itemButton.text = [_controllers[pageIndex] tabTitle];
    itemButton.touchUp = ^(UIButton *sender) {
        for (UIButton *button in _buttons) button.superview.tintColor = UI.toolBarInactiveButtonTextColor;
        sender.superview.tintColor = UI.toolBarActiveButtonTextColor;
        [self showPage:pageIndex];
    };
    [_buttons add:itemButton];
    return itemButton;
}

- (UIToolbar *)createToolbarForItemView:(uint)pageIndex {
    UIToolbar *itemToolbar = [UIToolbar.alloc initWithFrame:CGRectMake(0, 0, 100, 44)];
    itemToolbar.tintColor = nil;
    itemToolbar.barStyle = _toolbar.barStyle;
    itemToolbar.translucent = _toolbar.translucent;
    UIBarButtonItem *imageItem = [_controllers[pageIndex] tabImageItem];
    imageItem.style = UIBarButtonItemStylePlain;
    imageItem.tintColor = nil;
    imageItem.imageInsets = UIEdgeInsetsMake(-10, 0, 0, 0);
    itemToolbar.items = @[
            [UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil],
            imageItem,
            [UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]
    ];
    return itemToolbar;
}

Ответ 4

Я решил эту проблему следующим образом:

[Button **setTitleColor**:[UIColor colorWithRed:129/255.0f green:124/255.0f blue:110/255.0f alpha:1.0f] forState:**UIControlStateHighlighted**];