【发布时间】:2019-03-23 18:50:14
【问题描述】:
我制作了一个自定义视图,其中有一个按钮,可以将视图从其父视图中删除。视图是从作为超级视图的视图控制器创建的。我已经在我的自定义视图类中为我的视图设置了约束,如下所示,但我想它们是有问题的。
// View Contstaints
translatesAutoresizingMaskIntoConstraints = false
leadingAnchor.constraint(equalTo: superview!.leadingAnchor, constant: 40).isActive = true
trailingAnchor.constraint(equalTo: superview!.trailingAnchor, constant: -40).isActive = true
heightAnchor.constraint(equalToConstant: 420).isActive = true
centerYAnchor.constraint(equalTo: superview!.centerYAnchor).isActive = true
backgroundColor = .white
layer.cornerRadius = 15
当我点击按钮时,我得到 Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value 从这个特定的视图约束
leadingAnchor.constraint(equalTo: superview!.leadingAnchor, constant: 40).isActive = true
我该如何解决这个问题?谢谢。
【问题讨论】:
-
自定义视图没有将自身添加到其父视图中,因此不应将其从其父视图中删除。我可能会创建一个协议,其中包含视图控制器(包含此自定义视图)符合的
removeCustomViewFromSuperview()之类的函数。当在自定义视图中点击按钮时,自定义视图的委托(即视图控制器)会调用该方法,并且视图控制器会从超级视图中删除该自定义视图。