gpt4 book ai didi

ios - 使用不同对象时未执行 UIButton 目标操作

转载 作者:行者123 更新时间:2023-11-30 12:46:12 26 4
gpt4 key购买 nike

我正在代码中生成一个按钮,并使用 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")
}
}

有人知道为什么会发生这种情况吗?

最佳答案

问题是,一旦 viewDidLoad 完成,您的 ui 变量就会消失。

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

关于ios - 使用不同对象时未执行 UIButton 目标操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41605990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com