swift - 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)
])
}
newForm
是UIView
在 nib 故事板中添加了按钮和 textFields 的 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
您的框架变得无效并且在接收触摸时不活跃
推荐阅读
- java - 此代码使用什么公式来计算 pf Pi 的值?
- python - 在 Python 中,当列表已排序且列表未排序时,为什么以下代码会给出不正确的答案?
- java - 就 DDD 而言,是否可以在域服务中为聚合根实体而不是聚合根存储库实现 crud 逻辑?
- python - 如何从多个 vCenter 获取所有 vm 的详细信息?
- powerbi - Power Query : 会计月日数 WorkingDay
- javascript - Discord.js - 正确使用:for (const guild of client.guilds.cache)?
- javascript - 拒绝执行脚本并启用严格的 MIME 类型检查
- .net - dotnet 核心中的 DefaultModelBinder 替代品
- regex - 如何为 AWS 资源制作正则表达式
- ios - Flutter iOS Firebase Analytics 和 Crashlytics 未显示