ios 如何使用 UIButton 作为切换按钮?

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

How to use UIButton as Toggle Button?

iosiphoneuibuttonrubymotionrmq

提问by Anthony

I am trying to create a toggle button for each cell in my table. When pressed, it will change the image and when pressed again it will change the image again -- Toggle.

我正在尝试为表格中的每个单元格创建一个切换按钮。按下时,它将更改图像,再次按下时,它将再次更改图像——切换。

In the UIButtonclass I don't see a selectedstate.

UIButton课堂上我没有看到selected状态。

I'm looking for a way to create a toggle button with UIButton so that I can change the state on each click.

我正在寻找一种使用 UIButton 创建切换按钮的方法,以便我可以在每次单击时更改状态。

This is how I'm doing it in rubymotionright now using rmq

这就是我rubymotion现在使用的方法rmq

@fav_button.on(:touch) do |sender|
  puts "pressed fav button for id: " + data[:id] + " and name: " + data[:name]
  #how do I change the state here?
end

回答by Jan Cássio

You can create toggle button easily, you just need to set respective images for respective states, after that, you can use the selectedproperty to toggle between these images.

您可以轻松创建切换按钮,您只需要为各个状态设置相应的图像,然后,您就可以使用该selected属性在这些图像之间切换。

I made a pure objective-c code to show how you can do that, but you can set the images anyway in Storyboards ou Xibs too, check out:

我制作了一个纯objective-c代码来展示你如何做到这一点,但你也可以在Storyboards ou Xibs中设置图像,请查看:

// First, set the images for normal state and selected state
[button setImage:normalImage forState:UIControlStateNormal];
[button setImage:selectedImage forState:UIControlStateSelected];



// Don't forget to add an action handler to toggle the selected property
[button addTarget:self action:@selector(buttonTouch:withEvent:) forControlEvents:UIControlEventTouchUpInside];



// Now, in your button action handler, you can do something like this:
- (void)buttonTouch:(UIButton *)aButton withEvent:(UIEvent *)event
{
  aButton.selected = !aButton.selected;
}

I hope this can help you.

我希望这可以帮助你。

回答by JaredH

Swift 4.0 Solution (using Storyboards)

Swift 4.0 解决方案(使用故事板)

First, ensure the UIButtonType is set to Customin the Attributes Inspector.

首先,确保在属性检查器中将UIButton类型设置为Custom

Ensure UIButton Type is set to Custom

确保 UIButton 类型设置为自定义

// Reference to UIButton in Storyboard
@IBOutlet weak var toggleButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    // assumes you have two images in the bundle/project 
    // called normal.png and selected.png.
    let normalImage = UIImage(named: "normal.png")
    let selectedImage = UIImage(named: "selected.png")

    toggleButton.setImage(normalImage, for: .normal)
    toggleButton.setImage(selectedImage, for: .selected)
}

Below screenshot demonstrates reference to toggleButtonin Storyboard, and Touch Up InsideEvent, ie: a user tapping the button, which fires off didPressButtonbelow.

下面的屏幕截图演示toggleButton了 Storyboard 和Touch Up InsideEvent 中的引用,即:用户点击按钮,在didPressButton下面触发。

enter image description here

在此处输入图片说明

@IBAction func didPressButton(_ sender: Any) {

    // if the button was selected, then deselect it.
    // otherwise if it was not selected, then select it.
    toggleButton.isSelected = !trackingButton.isSelected

    if toggleButton.isSelected {
        print("I am selected.")

    } else {
        print("I am not selected.")
    }
}

回答by Steve Ross

Since your question did mention rmq, here's an rmq way of doing it:

由于您的问题确实提到了 rmq,因此这是一种 rmq 方法:

In viewDidLoad:

viewDidLoad

@hello_world_label = rmq.append(UILabel, :hello_world).get
@button            = rmq.append(UIButton, :toggleable_button)

@button.on(:touch) do |sender|
  sender.selected = !sender.selected?
end

Note that the toggle is achieved by querying the button's actual state. If you need to remember this for later use, you might want to save that in an instance variable.

请注意,切换是通过查询按钮的实际状态来实现的。如果您需要记住这一点以备后用,您可能希望将其保存在一个实例变量中。

In your stylesheet:

在您的样式表中:

def toggleable_button(st)
  st.frame = {t: 200, w: 100, h: 24}
  st.image_normal = image.resource('toggle_me')
  st.image_selected = image.resource('toggled')
end

Note the use of image_selected. Well, this doesn't exist in rmq, but you can make that happen quite easily. If this is an rmq project, you'll have a stylers/ directory. In there, you should see ui_button_styler.rb. Here's the code to make the highlighted state a first-class citizen:

注意使用image_selected. 嗯,这在 rmq 中不存在,但是您可以很容易地做到这一点。如果这是一个 rmq 项目,您将拥有一个 stylers/ 目录。在那里,您应该看到 ui_button_styler.rb。这是使突出显示的状态成为一等公民的代码:

module RubyMotionQuery
  module Stylers
    class UIButtonStyler < UIControlStyler 

      def image_selected=(value)
        @view.setImage(value, forState:UIControlStateSelected)
      end
      def image_selected
        @view.imageForState UIControlStateSelected
      end

    end
  end
end

As you can see, your controller code remains clean, the initial settings of the button are shifted to the stylesheet and you have neatly extended rmq to understand the selected state.

如您所见,您的控制器代码保持干净,按钮的初始设置转移到样式表,并且您巧妙地扩展了 rmq 以了解选定状态。

回答by Hic Up

My easiest logic to toggle button image. :)

我切换按钮图像的最简单逻辑。:)

(IBAction)toggleButton:(id)sender {
       if (self.toggleButton.selected==YES) {
           [self.toggleButton setSelected:NO];
        }else{
       [self.toggleButton setSelected:YES];
       [self.toggleButton setImage:[UIImage imageNamed:@"favStar.png"]    forState:UIControlStateSelected];
       }

回答by Julfikar

You can do it in a very easy approach. First of all, in your viewDidLoadset tag for your button. Let's say self.toggleButton.tag = 111. Now in your button action function, you can toggle the button like :

你可以用一种非常简单的方法来做到这一点。首先,在您viewDidLoad的按钮设置标签中。让我们说self.toggleButton.tag = 111。现在在您的按钮操作功能中,您可以像这样切换按钮:

- (IBAction)toggling:(id)sender{
    if(self.toggleButton.tag == 111){
        //this is normal state
        [self.toggleButton setTitle:@"Less..." forState:UIControlStateNormal];
        self.toggleButton.tag = 222;
    }else{
        //selected state
        [self.toggleButton setTitle:@"More..." forState:UIControlStateNormal];
        self.toggleButton.tag = 111;
    }
}

You can change the image of the button like this [self.toggleButton setImage://some image forState:UIControlStateNormal];.It's the easiest way I think. Hope it will help.

您可以像这样更改按钮的图像。[self.toggleButton setImage://some image forState:UIControlStateNormal];这是我认为最简单的方法。希望它会有所帮助。