gpt4 book ai didi

ios - 自定义 UIView 类约束取决于 ParentView

转载 作者:行者123 更新时间:2023-11-29 05:55:49 24 4
gpt4 key购买 nike

我正在制作一个包含日期选择器的自定义 UIView 类。我想设置 View 约束来引用将调用我的自定义类的父 View 。这是我的以下代码。这就是我得到的线程 1: fatal error :解包可选值时意外发现 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



}


}

这是我创建自定义 View 并启动它的地方

    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
}

关于ios - 自定义 UIView 类约束取决于 ParentView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55180990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com