添加子视图后自定义视图不可点击

Custom view is not clickable after addSubview

查看 addSubview 之前的层次结构:

视图 > 表格视图

查看 addSubview 之后的层次结构:

视图 > 表格视图 && 视图 > 自定义视图

调用addSubview后,CustomView显示在TableView之上,因为它的frame较小,是在TableView之后添加的。但是,我在 CustomView 中有按钮和文本字段,其中 none 正在工作。即使当我点击 CustomView 时,TableView 的 scrollView 似乎也在捕获 tapGesture。我怎样才能使 CustomView 的按钮和文本字段接受触摸?

此外,CustomView 的背景颜色很清晰,在将 customView 添加到视图层次结构时显示下方的 tableView。我尝试在情节提要中以编程方式设置背景颜色,但它仍然停留在清晰状态。我该如何解决这个问题?

class masterViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

//blah blah
@IBOutlet weak var tableView: UITableView! // tableView is added in the storyboard

let newForm = NewFormView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
    newForm.backgroundColor = UIColor.white
    self.view.addSubview(newForm)
    newForm.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        newForm.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
        newForm.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
        ])
}

newForm 是一个 UIView nib,在 nib 故事板中添加了按钮和文本字段

您需要添加宽度和高度限制

NSLayoutConstraint.activate([
    newForm.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
    newForm.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
    newForm.widthAnchor.constraint(equalToConstant:300),
    newForm.heightAnchor.constraint(equalToConstant:300)
])

就像你做的那样

newForm.translatesAutoresizingMaskIntoConstraints = false

你的框架变得无效并且在接收触摸时不活跃