简体   繁体   English

点击时如何反复更改按钮?

[英]How to change button repeatedly when tapped?

Using Swift, how do I make a: 使用Swift,我该如何制作:

  1. Button with words "start", that changes to "pause" and vice versa when tapped? 单词“开始”的按钮,在点击时会变为“暂停”,反之亦然? Not just once, but can be done infinitely? 不只是一次,但可以无限地完成? (eg in a stopwatch app) (例如在秒表应用程序中)
  2. Custom image button that changes between 2 image when tapped, that can also be done (tapped & change) infinitely? 自定义图像按钮在点击时在2个图像之间切换,也可以无限制地完成(点击和更改)?

In your storyboard, set the Default state title to "Start" and the Selected state title to "Pause" 在故事板中,将默认状态标题设置为“开始”,将选定状态标题设置为“暂停”

在此输入图像描述

在此输入图像描述

Or alternatively, if you're doing it in code: 或者,如果您在代码中执行此操作:

startPauseButton.setTitle("Start", forState: .Normal)
startPauseButton.setTitle("Pause", forState: .Selected)

In your IBAction func , toggle the button.selected property between true & false IBAction func ,将button.selected属性切换为truefalse

@IBAction func toggleStopwatch(button:UIButton) {
    if button.selected {
        // Pause the stopwatch
    } else {
        // Start the stopwatch
    }
    button.selected = !button.selected
}

You can also set different images for different states: Default , Highlighted , Selected , Disabled 您还可以为不同的状态设置不同的图像: 默认突出显示选定禁用

Step 1: Create a Bool variable 第1步:创建Bool变量

var isPlaying:Bool = false

Step 2: Connect your button with this IBAction method: 第2步:使用此IBAction方法连接您的按钮:

@IBAction func btnStartStop(sender: UIButton) {
    if isPlaying{

        isPlaying = false
        sender.setTitle("Pause", forState: UIControlState.Normal)
        sender.setImage(pauseImage, forState: .Normal)
        //Pause Stopwatch
    }
    else{

        isPlaying = true
        sender.setTitle("Play", forState: UIControlState.Normal)
        sender.setImage(playImage, forState: .Normal)
      //Play Stopwatch
    }
  }

In the @IBAction of the button (assuming you are using storyboards), you change the title or image of the button to what you want. 在按钮的@IBAction中(假设您使用的是故事板),您可以将按钮的标题或图像更改为您想要的内容。 You can also check for the title or image and perform an action based on what you have. 您还可以检查标题或图像,并根据您拥有的内容执行操作。

@IBAction func pressbutton(sender: UIButton) {
    switch sender.titleLabel?.text {
        case "Play":
        play()
        case "Pause":
        pause()
    default:
        other()
    }
    sender.titleLabel?.text = "Whatever you want"
}

Or with images (assuming you have an images array somewhere that stores the images, which you should): 或者使用图像(假设你有一个存储图像的images阵列,你应该这样做):

@IBAction func pressbutton(sender: UIButton) {
    switch sender.imageView!.image! {
        case images[0]:
            play()
        case images[1]:
            pause()
    default:
        other()
    }
    sender.imageView?.image = UIImage(...)
}

Try this.... 尝试这个....

@IBAction func btnStopWatch(sender: UIButton) {
        if btnStopWatch.selected == true  {
            btnStopWatch.setTitle("stop", forState: UIControlState.Normal)
            btnStopWatch.setImage(stopImage, forState: UIControlState.Normal)
            btnStopWatch.selected = false
        } else {
            btnStopWatch.setTitle("start", forState: UIControlState.Normal)
            btnStopWatch.setImage(startImage, forState: UIControlState.Normal)
            btnStopWatch.selected = true
        }
    }

#1. #1。 Toggle a UIButton title 切换UIButton标题

With Swift 3, UIButton has a method called setTitle(_:for:) . 使用Swift 3, UIButton有一个名为setTitle(_:for:) setTitle(_:for:) has the following declaration: setTitle(_:for:)具有以下声明:

func setTitle(_ title: String?, for state: UIControlState)

Sets the title to use for the specified state. 设置用于指定状态的标题。

The following Playground code shows how to use setTitle(_:for:) in order to toggle the title of a button according to its state: 以下Playground代码显示如何使用setTitle(_:for:)以根据其状态切换按钮的标题:

import PlaygroundSupport
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white

        let button = UIButton(type: UIButtonType.system)
        button.addTarget(self, action: #selector(toggle(sender:)), for: UIControlEvents.touchUpInside)

        // Set button's states
        button.setTitle("Start", for: UIControlState.normal)
        button.setTitle("Pause", for: UIControlState.selected)

        // set layout
        view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        let horizontalConstraint = button.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        let verticalConstraint = button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint])
    }

    /// trigger action when button is tapped
    func toggle(sender: UIButton) {
        sender.isSelected = !sender.isSelected
        print("Button state: \(sender.isSelected)")
    }

}

let vc = ViewController()
PlaygroundPage.current.liveView = vc

Preview your view controller in the Playground assistant editor using View > Assistant Editor > Show Assistant Editor 使用“ 视图” >“ 助理编辑器” >“ 显示助理编辑器”在Playground助手编辑器中预览视图控制器


#2. #2。 Toggle a UIButton image 切换UIButton图像

UIButton has a method called setImage(_:for:) . UIButton有一个名为setImage(_:for:)的方法setImage(_:for:) setImage(_:for:) has the following declaration: setImage(_:for:)具有以下声明:

func setImage(_ image: UIImage?, for state: UIControlState)

Sets the image to use for the specified state. 设置要用于指定状态的图像。

The following Playground code shows how to use setImage(_:for:) in order to toggle the title of a button according to its state: 以下Playground代码显示如何使用setImage(_:for:)以根据其状态切换按钮的标题:

import PlaygroundSupport
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white

        let button = UIButton()
        button.addTarget(self, action: #selector(toggle(sender:)), for: UIControlEvents.touchUpInside)

        // Set button's states
        button.setImage(UIImage(named: "on.png"), for: UIControlState.normal)
        button.setImage(UIImage(named: "off.png"), for: UIControlState.selected)

        // set layout
        view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        let horizontalConstraint = button.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        let verticalConstraint = button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        let heightConstraint = button.heightAnchor.constraint(equalToConstant: 100)
        let widthConstraint = button.widthAnchor.constraint(equalToConstant: 100)
        NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, heightConstraint, widthConstraint])
    }

    /// trigger action when button is tapped
    func toggle(sender: UIButton) {
        sender.isSelected = !sender.isSelected
        print("Button state: \(sender.isSelected)")
    }

}

let vc = ViewController()
PlaygroundPage.current.liveView = vc

Preview your view controller in the Playground assistant editor using View > Assistant Editor > Show Assistant Editor 使用“ 视图” >“ 助理编辑器” >“ 显示助理编辑器”在Playground助手编辑器中预览视图控制器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM