【问题标题】:UIButton target action not executed when using a different object使用不同对象时未执行 UIButton 目标操作
【发布时间】:2017-01-12 05:51:46
【问题描述】:

我在我的代码中使用生成按钮,并在按下按钮时使用 addTarget() 方法打印“Hi”。代码如下。

override func viewDidLoad() {
    super.viewDidLoad()
    let smartCarRequest = SmartCarOAuthRequest(clientID: "", redirectURI: "smartcar://oidc.com", scope: ["read_vehicle_info", "read_odometer"], development: true)

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.smartCarSDK = SmartCarOAuthSDK()
    let sdk = appDelegate.smartCarSDK
    var ui = SmartCarOAuthSDK()

    print(sdk!)
    print(ui)

    ui.generateButton(for: OEM(oemName: OEMName.mock), in: self.view.subviews[0])
}

目前,sdk 和 ui 变量都是 SmartCarOAuthSDK 对象。但是使用 sdk 变量生成按钮和动作会成功执行动作,而使用 ui 变量不会打印“Hi”。按钮生成代码如下。

class SmartCarOAuthSDK {

    init() {
    }

    func generateButton(for oem: OEM, in view: UIView) -> UIButton {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
        button.backgroundColor = hexStringToUIColor(hex: oem.oemConfig.color)
        button.setTitle("LOGIN WITH " + oem.oemName.rawValue.uppercased(), for: .normal)
        button.layer.cornerRadius = 5

        button.addTarget(self, action: #selector(pressed(_:)), for: .touchUpInside)

        view.addSubview(button)
        return button
    }  

    @objc func pressed(_ sender: UIButton) {
        print("Hi")
    }
}

有人知道为什么会这样吗?

【问题讨论】:

    标签: ios iphone swift uibutton


    【解决方案1】:

    问题是您的ui 变量在viewDidLoad 完成后立即消失。

    为避免这种情况,您需要将变量声明为类级变量。

    【讨论】:

      【解决方案2】:

      变量“ui”是属于方法“viewDidLoad()”的本地对象。 viewDidLoad 结束后会被销毁。这就是 ui 变量不再起作用的原因。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-03
        • 2013-08-27
        • 2019-10-08
        • 1970-01-01
        相关资源
        最近更新 更多