iOS Development
ios – UIButton’s addTarget not working in Swift

I am engaged on an iOS app in Swift, and I’ve encountered a difficulty with a UIButton’s addTarget not working as anticipated. I’ve tried to arrange a button to set off an motion, however for some motive, it is not responding to faucets. I’ve supplied my code beneath for reference.
class ErrorMessageView: UIView {
let tryButton = UIButton()
non-public lazy var buttonView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
non-public func configureTryButton() {
tryButton.setTitle("Strive Once more", for: .regular)
tryButton.addTarget(self, motion: #selector(self.buttonTapped), for: .touchUpInside)
tryButton.translatesAutoresizingMaskIntoConstraints = false
}
var buttonTapHandler: (() -> Void)?
init() {
tremendous.init(body: .zero)
configureTryButton()
setupUI()
}
non-public func setupUI() {
buttonView.addSubview(tryButton)
addSubview(mainStackView)
}
@objc non-public func buttonTapped() {
buttonTapHandler?()
}
}
extension UIViewController {
func showErrorMessageWithTryButton(tapHandler: @escaping () -> ()) {
DispatchQueue.major.async {
let errorView = self.setupErrorMessageWithButton(tapHandler: tapHandler)
self.view.addSubview(errorView)
}
}
non-public func setupErrorMessageWithButton(tapHandler: @escaping () -> ()) -> UIView {
let loadingView = UIView(body: .zero)
DispatchQueue.major.async {
let errorView = ErrorMessageView()
loadingView.addSubview(errorView)
errorView.buttonTapHandler = tapHandler
errorView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
errorView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
errorView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
errorView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20),
errorView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20),
])
}
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
tremendous.viewDidLoad()
self.showErrorMessageWithTryButton {
self.reloadPage()
}
}
func reloadPage() {
print("Reload Web page")
}
}
I’ve adopted the usual setup for including a goal motion to a UIButton, however it’s nonetheless not working. Tapping the button does not set off the buttonTapped operate. I am making an attempt to name the reloadPage operate in my ViewController when the button is tapped, however it’s not occurring.
Thanks upfront in your assist!
Further Info:
Xcode model: 14.2
iOS model/machine: 16.2 / Simulator iPhone 14 Professional Max
Credit: www.ismmailgsm.com