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