Reputation: 4984
I have simply UIViewController
class:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var _ = Test(parentView: view)
}
}
and another class:
import UIKit
class Test: NSObject {
let parentView: UIView
init(parentView: UIView) {
self.parentView = parentView
super.init()
addButton()
}
}
extension Test {
func addButton() {
let button = UIButton(type: .custom)
button.frame.size = CGSize(width: 100, height: 100)
button.addTarget(self, action: #selector(tap(_:)), for: .touchUpInside)
button.backgroundColor = UIColor.red
parentView.addSubview(button)
}
func tap(_ sender: UIButton) {
print("Tap")
}
}
Test
class inherits NSObject
because without it I get compilator massage Argument of '#selector' refers to instance method 'tap(sender:)' that is not exposed to Objective-C
.
The problem is that method tap(sender: UIButton)
does not call. I don't know why.
(Swift 3, Xcode 8.2.1, appTarget: iOS 9.0)
I edited implementation of Test
class according @vadian suggestions but it still does not work.
When I move Test
class implementation to ViewController
everything works but I don't want to do this. Why this not work in separate class?
Upvotes: 3
Views: 326
Reputation: 72410
I have test your project the problem is in this line var _ = Test(parentView: view)
, where you are creating object of your custom class Test
. So after th viewDidLoad
its instance is loss or deinit. Thats the reason you are not getting action call with button.
To solve the issue declare one instance property of type Test
inside your ViewController
class and initialize this property in viewDidLoad
. Now it will call action when you tap on button.
class ViewController: UIViewController {
var test: Test?
override func viewDidLoad() {
super.viewDidLoad()
self.test = Test(parentView: view)
}
}
Upvotes: 3