class 动态添加未响应 swift 中的触摸

class added dynamically doesn't respond touched in swift

我声明 TestClass 包含按钮和 textField 并对其进行约束,然后将此 class 添加到视图控制器

import Foundation
import UIKit

class TestClass : UIView {

    let testButton : UIButton = {
        let button = UIButton()
        button.setTitle("Test", for: .normal)
        button.setTitleColor(.red ,for:.normal)
        return button
    }()

    let testInput : UITextField = {
        let input = UITextField()
        input.placeholder = "type here"
        return input
    }()


    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    func setupView(){

        addSubview(testButton)
        addSubview(testInput)

        testButton.translatesAutoresizingMaskIntoConstraints = false
        testInput.translatesAutoresizingMaskIntoConstraints  = false

        testButton.topAnchor.constraint(equalTo: self.topAnchor, constant: 20).isActive = true
        testButton.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20).isActive = true
        testButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
        testButton.widthAnchor.constraint(equalToConstant: 50).isActive = true

        testInput.topAnchor.constraint(equalTo: self.topAnchor, constant: 70).isActive = true
        testInput.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20).isActive = true
        testInput.heightAnchor.constraint(equalToConstant: 30).isActive = true
        testInput.widthAnchor.constraint(equalToConstant: 100).isActive = true

    }



    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


}

在 viewDidLoad 中我添加了这个 class 它出现了。 但是当我点击 textField 或按钮时它没有响应

class ViewControll : UIViewController {

    let newClass : TestClass = {
        let view = TestClass()
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(newClass)
        newClass.frame.size = CGSize(width: 200, height: 200)
        newClass.translatesAutoresizingMaskIntoConstraints = false
        newClass.topAnchor.constraint(equalTo: contView.topAnchor, constant: 300).isActive = true
        newClass.leadingAnchor.constraint(equalTo: contView.leadingAnchor, constant: 30).isActive = true
        newClass.testButton.addTarget(self, action: #selector(prnt), for: .touchUpInside)

    }
    @objc func prnt(){
        print("bla bla bla")
    }
}

当我点击按钮或点击 textField 时没有任何反应 谁能帮帮我

约束未定义 TestClass 的高度和宽度 - 设置框架不起作用。您还需要为此添加约束,例如,在 viewDidLoad 方法中:

newClass.heightAnchor.constraint(equalToConstant: 200).isActive = true
newClass.widthAnchor.constraint(equalToConstant: 200).isActive = true