How to use UIButton as Toggle Button?

前端 未结 5 2284
庸人自扰
庸人自扰 2020-12-15 05:03

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.

5条回答
  •  执念已碎
    2020-12-15 05:32

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

    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:

    // 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.

提交回复
热议问题