定制Uiview类约束,具体取决于ParentView



我正在制作一个自定义的uiview类,该类容纳datepicker。我想设置视图约束,以引用将调用我自定义类的父视图。这是我的以下代码。这就是我得到的线程1:致命错误:未包装可选值

时出乎意料的发现
class CustomView: UIView {
    var datepicker:UIDatePicker!
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupConstraints()
    } // initiliaze the button like this CustomButton()
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    func setupDatePicker() {
        let datepicker = UIDatePicker()
        datepicker.minimumDate = Date()
    }
    func setupConstraints(){
        setupDatePicker()
        translatesAutoresizingMaskIntoConstraints = false
        leadingAnchor.constraint(equalTo: superview!.leadingAnchor, constant: 20).isActive = true // the error occurs here
        trailingAnchor.constraint(equalTo: superview!.trailingAnchor, constant: -20).isActive = true
        heightAnchor.constraint(equalToConstant: 60).isActive = true
        centerYAnchor.constraint(equalTo: superview!.centerYAnchor).isActive = true
        backgroundColor = .red

        addSubview(datepicker)
        datepicker.translatesAutoresizingMaskIntoConstraints = false
        datepicker.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 10).isActive = true
        datepicker.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true
        datepicker.heightAnchor.constraint(equalToConstant: 50).isActive = true
        datepicker.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true

    }

}

这是我创建自定义视图并启动它

的地方
    var customView: CustomView!
class ListViewController: UIViewController {
    @IBOutlet var tableView: UITableView!
    override func viewDidLoad() {
            super.viewDidLoad()
         customView = CustomView()
         view.addSubview(customView)
         view.bringSubviewToFront(customView)

谢谢您的时间。

您没有分配var datepicker:UIDatePicker!,因此是nil。尝试:

func setupDatePicker() {
    let datepicker = UIDatePicker()
    datepicker.minimumDate = Date()
    self.datepicker = datepicker
}

相关内容

  • 没有找到相关文章