动态添加的类无法快速响应

时间:2019-10-16 12:46:53

标签: ios swift programmatically

我声明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")
    }
}

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

1 个答案:

答案 0 :(得分:0)

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

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