【发布时间】: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")
}
}
有人知道为什么会这样吗?
【问题讨论】: