コード内でボタンを生成し、ボタンを押したときにaddTarget()メソッドを使用して "Hi"を出力しています。コードは以下の通りです。異なるオブジェクトを使用しているときにUIButtonターゲットアクションが実行されない
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")
}
}
これはなぜ起こっているのですか?