如何在iOS 7中设置UIBarButtonItem选中或突出显示的图像或色调?

时间:2013-10-11 14:36:27

标签: ios ios7 uibarbuttonitem

如何在iOS 7中向uibarbuttonitem提供正常状态和选中/突出显示的状态图像?有没有办法为uibarbuttonitem的正常和选定/突出显示状态提供色调颜色?

我不想使用uibutton作为uibarbuttonitem的视图!任何优雅的解决方案都将受到高度赞赏。

5 个答案:

答案 0 :(得分:2)

您可以将UIButton用作customView的{​​{1}},并为UIButton的UIBarButtonItemnormal状态设置两个不同的背景图片。然后,当点按该按钮时,您只需将selected州设置为selectedYES

NO

然后单击按钮时的in方法,更改状态

// Build right bar button
UIImage *normalButtonImage = [UIImage imageNamed:@"normal-button"];
UIImage *selectedButtonImage = [UIImage imageNamed:@"selected-button"];
CGRect rightButtonFrame = CGRectMake(0, 0, normalButtonImage.size.width,
                                           normalButtonImage.size.height);
UIButton *rightButton = [[UIButton alloc] initWithFrame:rightButtonFrame];
[rightButton setBackgroundImage:normalButtonImage forState:UIControlStateNormal];
[rightButton setBackgroundImage:selectedButtonImage forState:UIControlStateSelected];
[rightButton addTarget:self action:@selector(rightBarButtonPress)
         forControlEvents:UIControlEventTouchDown];
[orientationButton setShowsTouchWhenHighlighted:YES];
[orientationButton setSelected:NO];
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
[self.navigationItem setRightBarButtonItem:rightBarButton];

答案 1 :(得分:1)

您可以使用UIAppearance Protocol Reference

执行此操作
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], UITextAttributeTextColor, [UIColor clearColor], UITextAttributeTextShadowColor, nil];

[[UIBarButtonItem appearance] setTitleTextAttributes:options forState:UIControlStateNormal];

您可能还必须使用:

[[UINavigationBar appearance] setTintColor:[UIColor redColor]];

答案 2 :(得分:1)

根据this answer,我做了一些额外的事情,在这里有一个答案。我有自定义的UITabBarController,它与StoryBoard文件中的UITabBarController链接。因此,为了在取消选择TabBar时删除iOS提供的自动色调,我最终以这种方式删除它。图像可以是各种各样的图像,但只是recommended here的方式。在这里:

NSArray *navConArr = self.viewControllers;//self is custom UITabBarController
UINavigationController *naviOne = [navConArr objectAtIndex:0];//I have 3 different tabs, objectAtIndex:0 means the first tab navigation controller
UITabBarItem *naviBtn  = naviOne.tabBarItem;
UIImage *image = [[UIImage imageNamed:@"iconNaviOne"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[naviBtn setSelectedImage:image];
[naviBtn setImage:image];

因此,当从此选项卡移动到另一个选项卡并将其保留为未选中(默认为灰色)色调时,可以将其设置为提供的图像。值得庆幸的是,这就像一个魅力(:

答案 3 :(得分:0)

以下是axios.post('http://localhost:5000/api/bookmarks', { tags: ["banana", "orange"] }) .then(result => console.log('Result:', result.data)) .catch(err => console.log('Error:', err.response.data.errors.url.message)); 解决方案:

Swift 4

答案 4 :(得分:0)

AFAIK 没有原生/优雅的解决方案可以做到这一点,我所做的是跟踪按钮的状态并基于此更改 tintColor

@objc func handleButton() {
    if yourButtonIsSelected {
        yourButton.tintColor = unselectedColor
    } else {
        yourButton.tintColor = selectedColor
    }
}

请注意,无法知道是否选择了 UIBarButtonItem,因此您也需要提供此信息(在我的示例中为 yourButtonIsSelected