我想仅使用 Swif 3 代码创建和自定义 JTAppleCalendarView,即不使用 Interface Builder、 Storyboard或 XIB 文件。
我可以通过代码创建海关标签,但是当我尝试创建 JTAppleCalendarView 时,我根本无法更改框架值,无论是 heightAnchor 还是 widthAnchor。这样,我的日历就不会显示了。
我附上了我的自定义 UIViewController 的初始化代码(它实现了数据源和委托(delegate)协议(protocol)):
init(frame: CGRect) {
super.init(nibName: nil, bundle: nil)]
self.view = UIView(frame: frame)
self.view.backgroundColor = UIColor.green
let margins = self.view.layoutMarginsGuide
let calendar = JTAppleCalendarView()
print("CalendarView frame: ", calendar.frame)
calendar.dataSource = self
calendar.delegate = self
calendar.cellInset = CGPoint(x: 0, y: 0)
calendar.backgroundColor = UIColor.white
calendar.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(calendar)
calendar.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
calendar.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
calendar.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
//calendar.widthAnchor.constraint(equalTo: margins.widthAnchor).isActive = true
calendar.heightAnchor.constraint(equalToConstant: 400).isActive = true
}
每当我更改 calendar.heightAnchor、calendar.widthAnchor 或 calendar.frame 时,我都会收到错误“Unexpectedly found nil while unwrapping an Optional value.”。
我遵循了库教程,但是他们只展示了使用 Interface Builders 的创建,我没有在我的项目中使用它。从技术上讲,该组件只是一个自定义 UIView,所以我对这个错误感到困惑。
最佳答案
在上面的代码中,我忘记了注册单元格。 解决了使用类似以下内容注册单元格的问题:calendar.registerCellViewClass(type: SomeCellClass.self)。
到目前为止,它适用于一个简单的项目。我没有在 Playground 上进行测试。
关于ios - 在代码中创建 JTAppleCalendarView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41203728/