我做了一个简单的代码来澄清我的问题。当我在我的 iPhone 上运行我的应用程序时它工作正常,但是当我按下主页按钮 - 无论是在模拟器上还是在我的真实 iPhone 上 - 并再次按下应用程序图标时,应用程序运行,但应用程序的按钮“TestButtonAction 不起作用。相同当我按下电源/ sleep 按钮并再次打开它时出现问题。 同样的问题,当我双击主页按钮并通过将它的窗口滑开来终止我的应用程序,然后再次重新运行它时按钮不起作用或在控制台中打印“正确的图像” 这是我的代码,谢谢。
//
// ViewController.swift
// TestingHomeButton
//
// Created by Samuel Oncy on 4/25/18.
// Copyright © 2018 Samuel Oncy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var TestButtonOutlet: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func TestButtonAction(_ sender: UIButton) {
if(TestButtonOutlet.imageView?.image == UIImage(named:"NatureView")){
print("Right Image")
}
}
}
最佳答案
只需将 UIImage 设为全局变量,如果你想在 If 中进行比较。
其他方法也可以解决同样的问题——Tag是对的。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var TestButtonOutlet: UIButton!
var image = UIImage (named: "NatureView")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func TestButtonAction(_ sender: UIButton) {
// print(TestButtonOutlet.imageView?.image == UIImage(named:"NatureView"))
if (TestButtonOutlet.currentImage == image) {
print(TestButtonOutlet.currentImage)
}
}
}
关于ios - 当我按下 iPhone 主页按钮、 sleep /电源按钮或终止我的应用程序并再次重新运行它时,TestButtonAction 不打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50021047/