ios - 当我按下 iPhone 主页按钮、 sleep /电源按钮或终止我的应用程序并再次重新运行它时,TestButtonAction 不打印

标签 ios swift xcode

我做了一个简单的代码来澄清我的问题。当我在我的 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/

相关文章:

ios - Xcode 9、Ionic、Cordova、iOS 模拟器

ios - 如何通过 ssh 运行 xcodebuild 命令?

ios - 当 UICollectionViewCell 的 subview 启用了 userInteraction 时,UIMenuController 不显示

swift - 为什么 Apple 选择使用嵌套结构类型来替换 'String' 类型参数?

ios - 在 Segue 中传递数据时 void _UIPerformResizeOfTextViewForTextContainer 断言失败

ios - 无法在 swift 中解密使用 openssl -aes256 加密的字符串

ios - 如何从 Objective C 项目 App Delegate 调用 Swift?

iphone - iPhone/桌面应用程序的相同代码库

ios - 文本字段应该 swift 更改范围内的字符

ios - UITableView - 如何滚动标题部分以及表格 View 单元格?