首页 > 解决方案 > addSubview 后自定义视图不可点击

问题描述

查看之前的层次结构addSubview

视图 > 表格视图

之后查看层次结构addSubview

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

调用后addSubview,CustomView 显示在 TableView 的顶部,因为它的框架较小,并且是在 TableView 之后添加的。但是,我在 CustomView 中有按钮和文本字段,它们都不起作用。即使当我点击 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)
        ])
}

newFormUIView在 nib 故事板中添加了按钮和 textFields 的 nib

标签: swiftuitableviewuiview

解决方案


您需要添加宽度和高度约束

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

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


推荐阅读