我正在制作一个自定义的UIView类,其中包含一个日期选择器。我想设置视图约束以引用将调用自定义类的父视图。这是我的以下代码。这就是我得到的 线程1:致命错误:在展开可选值时意外发现nil
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)
谢谢您的时间。
答案 0 :(得分:0)
您没有分配var datepicker:UIDatePicker!
,所以它是nil
。
试试:
func setupDatePicker() {
let datepicker = UIDatePicker()
datepicker.minimumDate = Date()
self.datepicker = datepicker
}