IOS SWIFT-根据uibutton图片调用代码块

IOS SWIFT-call code block based on uibutton image

这是我试图让它工作的代码。我的目标是根据按钮的图像调用一段代码。该按钮根据之前的图像更改图像。

@IBOutlet weak var startFuncAButton: UIButton!

let navBtn = UIImage (named: "ArrowStraight")
let greenTimer = UIImage (named: "Timer")
let redTimer = UIImage (named: "TimerStop")

    @IBAction func startFuncA(sender: UIButton) {
    if self.startFuncAButton.imageView == greenTimer {
        println("button's image is green timer")
    }
    else if self.startFuncAButton.imageView == redTimer {
        println("button's image is red timer")
    }
    else if self.startFuncAButton.imageView == navBtn {
        println("button's image is arrow")
        NSLog("Start Navigation Button Pressed")
        self.navBar.hidden = true
        self.navigator = Navigator(route: self.route!)
        self.navigator?.HUD_delegate = self.navigationHUDView
        self.navigator?.locationUpdateDelegate = self
        self.navigationHUDView.hidden = false
        self.navigationHUDView.directionImageView.image = UIImage(named: "ArrowStraight")
        self.navigationHUDView.navigator = self.navigator
        self.navigationHUDView.backgroundColor = UIColor(red: 0.12, green: 0.13, blue: 0.16, alpha: 1.0)
        self.startFuncAButton.setImage(UIImage(named: "Timer"), forState: .Normal)

但是当我在应用程序中按下这个按钮时,没有任何反应。没有打印行发送到控制台。显然,我没有正确地执行条件。如何让它根据 IOS Swift 中的图像执行代码?

为了回答第一条评论,我扩展了我的代码段。正如您在最后一行中看到的,图像在两行中设置为 "Timer" 和 "ArrowStraight"(来自 let 语句)。

您正在测试 UImageView 是否等于 UIImage。改为这样做:

self.startFuncAButton.imageView.image == greenTimer
  1. UIButton 的 'imageView' 是一个 UIImageView。您试图将其等同于 UI 图片。它们永远不会是同一个对象。

  2. 依靠按钮的图像来执行条件代码是一种非常糟糕的实现方式。 UI(在您的情况下是要设置的图像)应取决于代码/逻辑(MVC 基础知识)。如果您根据图像执行条件代码,则您的逻辑取决于 UI.

  3. 你应该有一个标志(一个枚举)来表示当前的执行状态。您应该设置按钮的图像并根据标志在按钮点击时执行代码。

    枚举 TimerStatus:字符串 {

    案例绿色="Green"

    案例红色="Red"

    案例停止 = "Stopped"

    }

您可以在声明枚举变量时设置默认状态:

var timerStatus : TimerStatus = .Green


switch timerStatus {
case .Green:
    // Green status code
case .Red:
    // Red status code
case .Stopped:
    // Stopped status code
}