在Swift中动态添加的类不响应触摸

vecaoik1  于 2023-05-16  发布在  Swift
关注(0)|答案(1)|浏览(158)

我声明TestClass包含button和textField并对其进行约束,然后将这个类添加到视图控制器中

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中,我添加了这个类,它就出现了。但当我点击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")
    }
}

当我点击按钮或点击文本字段时,没有发生任何事情,任何人都可以帮助我,请

kkbh8khc

kkbh8khc1#

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

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

相关问题