ios 如何设置 UIButton 状态在按下后高亮显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7230019/
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 21:17:25  来源:igfitidea点击:

How to set the UIButton state to be highlighted after pressing it

ioscocoa-touchuikituibutton

提问by A for Alpha

I have a typical requirement wherein I need to keep a button in highlighted state after pressing it. I need to perform a task which should work only when a button is in highlighted state. Actually I am setting a button state to highlighted programatically.

我有一个典型的要求,我需要在按下按钮后将按钮保持在突出显示状态。我需要执行一个只有当按钮处于突出显示状态时才应该工作的任务。实际上,我正在以编程方式将按钮状态设置为突出显示。

[sender setHighlighted:YES];

[sender setHighlighted:YES];

And once the button is in highlighted state i need to perform another action.

一旦按钮处于突出显示状态,我需要执行另一个操作。

- (IBAction)changeState: (UIButton*)sender
{   
    if (sender.highlighted == YES)
    {
        [self performSomeAtion:sender];
    }
}

But, to my horror, whenever I press any button, the above condition is becoming true and the action is being performed repeatedly. Is there any way in which i can keep a UIButton's state to be highlighted after pressing it?

但是,令我恐惧的是,每当我按下任何按钮时,上述情况就会变为真,并且该操作会重复执行。有什么方法可以让我在按下 UIButton 后保持其状态突出显示?

EDIT- Actually I need to perform 3 different actions for 3 different states of the button. I am already making use of selected state and normal state. Now, I need to make use of the highlighted state.

编辑- 实际上我需要为按钮的 3 种不同状态执行 3 种不同的操作。我已经在使用选定状态和正常状态。现在,我需要利用突出显示的状态。

回答by Vijay-Apple-Dev.blogspot.com

[sender setSelected:YES]; 

or you can simulate this effect with two image for your UIButton (notselectedimage.pngand selectedimage.png), then keep track button state with a BOOL variable like BOOL buttonCurrentStatus;. Then in .h file:

或者,您可以使用 UIButton(notselectedimage.pngselectedimage.png)的两个图像模拟此效果,然后使用 BOOL 变量(如BOOL buttonCurrentStatus;. 然后在 .h 文件中:

BOOL buttonCurrentStatus;

and in .m file

并在 .m 文件中

// connect this method with Touchupinside function
- (IBAction)changeState:(UIButton*)sender
{
    /* if we have multiple buttons, then we can
       differentiate them by tag value of button.*/
    // But note that you have to set the tag value before use this method.

  if([sender tag] == yourButtontag){

    if (buttonCurrentStatus == NO)
    {
        buttonCurrentStatus = YES;
        [butt setImage: [UIImage imageNamed:@"selectedImage.png"] forState:UIControlStateNormal];
        //[self performSomeAction:sender];
    }
    else
    {
        buttonCurrentStatus = NO;
        [butt setImage:[UIImage imageNamed:@"notSelectedImage.png"] forState:UIControlStateNormal];
        //[self performSomeAction:sender];
    }   
  }
}

回答by Rajesh Loganathan

- (void)mybutton:(id)sender
{
    UIButton *button = (UIButton *)sender;
    button.selected = ![button isSelected]; // Important line
    if (button.selected)
    {
        NSLog(@"Selected");
        NSLog(@"%i",button.tag);
    }
    else
    {
        NSLog(@"Un Selected");
        NSLog(@"%i",button.tag);

    }
 }

回答by progrmr

The highlighted state is used to highlight the button whileit is being touched. A touch down event in the button highlights it. You should use the "selected" state instead.

突出显示状态用于在按钮被触摸突出显示按钮。按钮中的触地事件突出显示它。您应该改用“已选择”状态。

If what you want to do is perform an action after the button is pressed, don't attach your method to the state change event, attach your method to the TouchUpInside event.

如果您想做的是在按下按钮后执行操作,请不要将您的方法附加到状态更改事件,而是将您的方法附加到 TouchUpInside 事件。

回答by Hal

I just find a way, so I share it, just in case...

我只是找到了一种方法,所以我分享它,以防万一......

I kept my UIButton and set one image for each state (so you could go up to a 4 states button). I set the UserInteractionEnabled to NO -> This button won't receive any touch. The purpose of this first button is to show a state

我保留了我的 UIButton 并为每个状态设置了一个图像(因此您可以使用 4 个状态按钮)。我将 UserInteractionEnabled 设置为 NO -> 此按钮不会收到任何触摸。第一个按钮的目的是显示一个状态

I create a second custom UIButton with the same frame than the first one. For this one, none image will be set for the state (it's a fully transparent button). The purpose of this button is to catch the touch event. So I added a target to this button on the TouchUpInside event. And then when the event is fired, I change the state of the first button to Disabled, Highlighted, Selected, or none of these state (= Default state).

我创建了第二个自定义 UIButton,其框架与第一个框架相同。对于这个,不会为状态设置任何图像(它是一个完全透明的按钮)。这个按钮的目的是捕捉触摸事件。所以我在 TouchUpInside 事件上为这个按钮添加了一个目标。然后当事件被触发时,我将第一个按钮的状态更改为禁用、突出显示、选择或这些状态都没有(= 默认状态)。

Everything is working like a charm!

一切都像魅力一样工作!

回答by Kheldar

The way you describe it, you'd be better off subclassing UIView to create your own three-state button.

你描述它的方式,你最好继承 UIView 来创建你自己的三态按钮。

Actually, you should even implement your own multistate buttonView, and manage the state it's in internally via an array of PNG for the looks and an array of states to know how many times it's been pressed.

实际上,您甚至应该实现自己的多状态 buttonView,并通过用于外观的 PNG 数组和状态数组来管理它在内部所处的状态,以了解它被按下了多少次。

回答by Narayana

Use [sender setSelected: YES];, I think it will be useful to you.

使用 [sender setSelected: YES];,我想它会对你有用。

回答by Narayana

UIButton *btn_tmp=sender;
    if(!(btn_tmp.selected))
    {
[btn_temp setHighlighted:YES];

}

回答by John Henckel

For iOS 7 only: you should consider setting the image renderMode to UIImageRenderingModeAlwaysTemplate. You can then use the tintColor to represent various states.

仅适用于 iOS 7:您应该考虑将图像渲染模式设置为 UIImageRenderingModeAlwaysTemplate。然后您可以使用 tintColor 来表示各种状态。

see How to apply a tintColor to a UIImage?and

请参阅如何将 tintColor 应用于 UIImage?

see Tint a UIView with all its subviews

请参阅为 UIView 及其所有子视图着色

回答by BootMaker

The solution is tricky but it's possible.

解决方案很棘手,但这是可能的。

The problem is that you tried to change the highlighted status in the button action method, which I suppose makes a clean up or check process at the end of the action and switch the highlighted status. When you try to debug it you get the highlighted = 1 but it will change at the end.

问题是您尝试更改按钮操作方法中的突出显示状态,我想这会在操作结束时进行清理或检查过程并切换突出显示状态。当您尝试调试它时,您会得到突出显示的 = 1,但它最终会发生变化。

Strange but your "3 statuses button" is sometimes useful, when you'd like to keep a button in "highlighted" mode like the "selected" mode to get different action depending on the 3 statuses. The only problem that you couldn't analyze this or switch it to highlighted mode in the button action method as this will switch to highlighted mode immediately as the user push it AND switch it back at the end.

奇怪,但是当您希望将按钮保持在“突出显示”模式(如“选定”模式)以根据 3 种状态获得不同操作时,您的“3 种状态按钮”有时很有用。唯一的问题是您无法在按钮操作方法中对此进行分析或将其切换到突出显示模式,因为当用户按下它并在最后将其切换回时,这将立即切换到突出显示模式。

The solution is using a dispatch.

解决方案是使用调度。

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [theButton setHighlighted:YES];
});

This will do the trick and you could use the 3 statuses.

这将解决问题,您可以使用 3 种状态。

回答by OhadM

According to apple, UIButton has a property of imageView:

据苹果的UIButton有一个属性的ImageView

Although this property is read-only, its own properties are read/write.Use these properties to configure the appearance and behavior of the button's view

虽然这个属性是只读的,但它自己的属性是读/写的。使用这些属性来配置按钮视图的外观和行为

This means that you can set in the IB (in the storyboard) a picture for this button and set the highlighted picture:

这意味着您可以在 IB(在故事板中)为此按钮设置图片并设置突出显示的图片:

  1. Open the Attribute inspector.
  2. Under Buttonsection, choose an image.
  3. In the same section, change the State Config to Highlighted. Notice the image you chose under default is now gone and now you can set a new picture for the Highlighted.
  4. Now you have a button with 2 state config and all you have to do during runtime to change the button.highlighted = true. Also, check the UIControlunder Configuring the Control's Attributesfor more states.
  1. 打开属性检查器。
  2. 按钮部分下,选择一个图像。
  3. 在同一部分中,将状态配置更改为突出显示。请注意,您在默认情况下选择的图像现已消失,现在您可以为突出显示设置新图片。
  4. 现在您有一个带有 2 个状态配置的按钮,并且您需要在运行时更改button.highlighted = true. 此外,检查配置控件的属性下的UIControl以了解更多状态。

You can also do it programatically as follows:

您也可以按如下方式以编程方式执行此操作:

Swift (and almost the same in Objective-C):

Swift(在 Objective-C 中几乎相同):

// Setting the highlighted image
self.someButton.imageView?.highlightedImage = UIImage(named: "imageNameFromImageAssest")
// someButton will now some the highlighted image and NOT the image set in the IB
self.someButton.imageView?.highlighted = true