自定义UIView类约束,具体取决于ParentView
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义UIView类约束,具体取决于ParentView相关的知识,希望对你有一定的参考价值。
我正在创建一个包含日期选择器的自定义UIView类。我想设置视图约束来引用将调用我的自定义类的父视图。这是我的以下代码。这就是我得到的线程1:致命错误:在展开Optional值时意外地发现了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)
感谢您的时间。
答案
你没有分配var datepicker:UIDatePicker!
所以它是nil
。尝试:
func setupDatePicker() {
let datepicker = UIDatePicker()
datepicker.minimumDate = Date()
self.datepicker = datepicker
}
以上是关于自定义UIView类约束,具体取决于ParentView的主要内容,如果未能解决你的问题,请参考以下文章