ios 以编程方式突出显示 UIBarButtonItem

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8267758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:35:36  来源:igfitidea点击:

programmatically highlight UIBarButtonItem

ioscocoauibarbuttonitem

提问by Ckoeny

after tapping the 'record' BarButtonItem I would like to keep it programmatically highlighted until the recording is over. The highlighting graphics of iOS are very good, therefor I would like to remain or set that state.

点击“记录”BarButtonItem 后,我想以编程方式将其突出显示,直到记录结束。iOS的高亮图形非常好,所以我想保持或设置那个状态。

Up to now I found 'setSelected' and 'setHighlighted' but these do not work on a UIBarButtonItem. Any suggestions on how to solve this? Thank you in advance, Koen.

到目前为止,我发现了 'setSelected' 和 'setHighlighted',但这些在 UIBarButtonItem 上不起作用。有关如何解决此问题的任何建议?提前谢谢你,科恩。

采纳答案by Michael Dautermann

setSelectedand setHighlightedwork fine on UIControls, but not UIBarButtonItems (which are not UIControls).

setSelectedsetHighlighted在 UIControls 上正常工作,但不适用于 UIBarButtonItems(不是 UIControls)。

I'd recommend using UIBarButtonItem's - (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics(documentation linked) method to change the background image to something that mimics highlighting.

我建议使用 UIBarButtonItem 的 - (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics(文档链接)方法将背景图像更改为模拟突出显示的内容。

You can also set a custom UIView on the item which also mimics highlighting (see the customViewproperty).

您还可以在项目上设置自定义 UIView,该项目也模拟突出显示(请参阅customView属性)。

回答by Cameron Lowell Palmer

If you add a UIBarButtonItemwith a UIButtonbacking it, you can just ask for the CustomView.

如果你添加了UIBarButtonItem一个UIButton支持它,你可以只要求 CustomView。

UIBarButtonItem with a backing UIButton

带有支持 UIButton 的 UIBarButtonItem

UIButton *button = (UIButton *)[self.barButtonItem customView];
[button setSelected:YES];

回答by Patrick

If you absolutely want to use the default graphics, you could initialize your button item as

如果您绝对想使用默认图形,则可以将按钮项初始化为

UIBarButtonItem *toggleButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"MyButton" 
                                                                     style:UIBarButtonItemStyleBordered 
                                                                    target:someObject 
                                                                    action:@selector(doSomething:)];

and toggle it with

并切换它

toggleButtonItem.style = (toggleButtonItem.style == UIBarButtonItemStyleBordered) 
                         ? UIBarButtonItemStyleDone : UIBarButtonItemStyleBordered;

You would also need to use the style property to read the current state.

您还需要使用 style 属性来读取当前状态。

BOOL isSelected = (toggleButtonItem.style == UIBarButtonItemStyleDone)

回答by ThePunisher

You create an outlet of this button for example btnMoreOutand you do:

例如btnMoreOut,您创建此按钮的出口,然后执行以下操作:

btnMoreOut.tintColor = [UIColor colorWithRed:0.882 green:0.722 blue:0.169 alpha:1];

I hope this helps..Good luck :)

我希望这会有所帮助..祝你好运:)

回答by smileBot

1) Get a reference to your bar button.

1) 获取对您的栏按钮的引用。

2) Using the style property, assign it to UIBarButtonItemStyleDone, or UIBarButtonItemStylePlain on the basis of some state.

2) 使用 style 属性,根据某些状态将其分配给 UIBarButtonItemStyleDone 或 UIBarButtonItemStylePlain。

NB. You can get the state in various ways. For instance, using NSUserDefaults, save a key value pair there. Pull out the value, and grab some BOOL representation to test against. Then write this line:

注意。您可以通过多种方式获取状态。例如,使用 NSUserDefaults,在那里保存一个键值对。拉出值,并获取一些 BOOL 表示进行测试。然后写这一行:

 self.myButton.style = self.someState ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain;

Or with the defaults all nested like this:

或者使用所有嵌套的默认值,如下所示:

self.myButton.style = [[NSUserDefaults standardUserDefaults] 
boolForKey:@"someKey"] ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain;

Without the ternary operator:

没有三元运算符:

if ([[NSUserDefaults standardUserDefaults] 
    boolForKey:@"someKey"]) {
self.myButton.style = UIBarButtonItemStyleDone; 
} else {
self.myButton.style = UIBarButtonItemStylePlain;
}

回答by leanne

p.a.'s answer, converted for Xcode 9, Swift 4.
The idea is that the .donestyle highlights - or bolds, in Swift 4 - the button text.

pa 的答案,已转换为 Xcode 9、Swift 4。
这个想法是.done样式在 Swift 4 中突出显示 - 或粗体- 按钮文本。

Initialize the button item in an un-highlighted state:

在未突出显示的状态下初始化按钮项:

let toggleButtonItem = UIBarButtonItem(title: "MyButton",
                                       style: .plain,
                                       target: self,
                                       action: #selector(doSomething))

Toggle the button item to a highlighted state using a ternary operator, like so:

使用三元运算符将按钮项切换到突出显示状态,如下所示:

toggleButtonItem.style = (toggleButtonItem.style == .plain) ?
                         toggleButtonItem.style = .done : toggleButtonItem.style = .plain

Or, alternatively, toggle the highlight state with a regular if/elsestatement like this instead:

或者,也可以使用如下的常规if/else语句切换高亮状态:

if toggleButtonItem.style == .plain {
    toggleButtonItem.style = .done
}
else {
    toggleButtonItem.style = .plain
}

And, to set up a boolean value to check if the button item is highlighted:

并且,要设置一个布尔值来检查按钮项是否突出显示:

var isHighlighted: Bool = (toggleButtonItem.style == .done)

Notes:

笔记:

  • The borderedstyle was deprecated in iOS 8, so I used .plainhere instead. They both present the button item's text in an unhighlighted state.
  • The #selectorfunction must either be an @IBAction, or it must be prefixed with @objc, to avoid "Objective-C inference" issues. For example:

    @objc func doSomething() { ... }
    

    or, if you've connected an action to the button item:

    @IBAction func doSomething() { ... }
    

    Both of these function declarations tell the compiler that they're using Objective-C-based functionality. This is required because #selectoris an Objective-C thing under the hood, and in Swift 4 you have to state this, rather than letting the compiler inferwhat's going on as it has done previously.

  • bordered样式在 iOS 8 中已弃用,因此我.plain在这里使用。它们都以未突出显示的状态呈现按钮项的文本。
  • #selector函数必须是@IBAction,或者必须以 为前缀@objc,以避免“Objective-C 推理”问题。例如:

    @objc func doSomething() { ... }
    

    或者,如果您已将操作连接到按钮项:

    @IBAction func doSomething() { ... }
    

    这两个函数声明都告诉编译器它们正在使用基于 Objective-C 的功能。这是必需的,因为#selector它是 Objective-C 底层的东西,在 Swift 4 中你必须声明这一点,而不是让编译器像以前那样推断发生了什么。

回答by Allan Scofield

You can try this (Swift):

你可以试试这个(斯威夫特):

    func setupInterface(){

    var myButton = UIBarButtonItem()
    if (your_condition){
      myButton = UIBarButtonItem(image: UIImage(named: "img_selected"), style: .Plain, target: self, action: Selector("DoSomething:"))
    }
    else{
        myButton = UIBarButtonItem(image: UIImage(named: "img_unselected"), style: .Plain, target: self, action: Selector("DoSomething:"))
    }
    navigationItem.rightBarButtonItem = myButton
  }

Call setupInterface() in ViewDidLoad and another function in your code.

在 ViewDidLoad 和代码中的另一个函数中调用 setupInterface()。

回答by Akhrameev

If you wanna change just title attributes (for example, title color), you can call setTitleTextAttributes:forState:

如果您只想更改标题属性(例如,标题颜色),您可以调用 setTitleTextAttributes:forState:

For me, it works more stable than setTintColor:(changing tint color breaks during unwind segue push animation).

对我来说,它比setTintColor:(在展开转场推送动画期间改变色调颜色中断)更稳定。

回答by ankit.tlp

You can use two images for the two states of the button like for one state "UIControlStateNormal" you can use an image for the normal condition.

您可以将两个图像用于按钮的两种状态,例如对于一种状态“UIControlStateNormal”,您可以将图像用于正常状态。

And then when the button is pressed, set the other image which shows it pressed, then the image with a check using isSelected method of UIButton.

然后当按钮被按下时,设置显示它被按下的另一个图像,然后使用 UIButton 的 isSelected 方法检查图像。

Hope this makes some sense to you.

希望这对你有意义。